/* 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 OR ALTER PROCEDURE SP_COPIA_ATIVIDADES_MUNICIPAIS
 (
  CODCIDNOVA INTEGER,
  CODCIDCOPIAR INTEGER
  )
AS
 BEGIN EXIT; END
^

CREATE PROCEDURE SP_TIPODESCIDIOMAS RETURNS(BDCODTIPODESCIDIOMA INTEGER,
BDCLASSIFICACAO VARCHAR(100),
BDCONFIGURA DM_BOOLEAN,
BDPERMITEABREVIADO DM_BOOLEAN,
BDPLANO INTEGER,
BDNIVEL INTEGER,
BDNIVEL1 VARCHAR(100),
BDNIVEL2 VARCHAR(100),
BDNIVEL3 VARCHAR(100),
BDCONSTANTE VARCHAR(30),
BDDESCRICAO VARCHAR(100))
 AS
 BEGIN SUSPEND; END
^

CREATE PROCEDURE SP_VRHF_PBM_NO_ANO(PREMP VARCHAR(32700),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE PROCEDURE VEF_COPIA_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
IMPOSTO VARCHAR(10))
 AS
 BEGIN EXIT; END
^

CREATE PROCEDURE VSUC_SP_COPIA_CONFIG_IDIOMAS(PRIDIOMA INTEGER,
PRCODPLANO_DE INTEGER,
PRCODPLANO_PARA INTEGER,
PRPLANO INTEGER,
PROPCAOTROCA INTEGER)
 AS
 BEGIN EXIT; END
^


/* Alter View (Drop, Create)... */
/* Drop altered view: VW_TINDVAL */
SET TERM ; ^

DROP VIEW VW_TINDVAL;

/* Create altered view: VW_TINDVAL */
/* Create view: VW_TINDVAL */
CREATE VIEW VW_TINDVAL(
BDCODIND,
BDREFIND,
BDDATAIND,
BDVALIND)
 AS 
SELECT
  BDCODIND,
  CAST((overlay(BDREFIND placing '' FROM 7 FOR 2)) AS INTEGER),
  CAST(SUBSTRING(BDREFIND FROM 5 FOR 2) ||'/'|| REPLACE(CASE WHEN CHAR_LENGTH(BDREFIND) > 6 THEN OVERLAY(BDREFIND PLACING '' FROM 1 FOR 6) ELSE '01' END, '00', '01') ||'/'|| OVERLAY(BDREFIND PLACING '' FROM 5 FOR 4) AS DATE),
  COALESCE(BDVALIND, 0)

FROM
  TINDVAL
;

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

/* Create altered view: VW_VEF_TOTEXP_UF_ENT_GIASP */
/* 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)
  AND itens.BDVLRCONTAB > 0

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
;

/* Drop altered view: VW_VEF_TOTEXP_UF_SAI_GIASP */
DROP VIEW VW_VEF_TOTEXP_UF_GIASP;

DROP VIEW VW_VEF_TOTEXP_UF_SAI_GIASP;

/* Create altered view: VW_VEF_TOTEXP_UF_SAI_GIASP */
/* 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 = SAI.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 = SAI.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
;

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

ALTER PROCEDURE SP_RETORNA_EMPRESA_FILIAIS(PRCODEMP INTEGER,
PRREFEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

/*  Empty SP_VEF_RETORNA_SALDO_DIME for SP_RETORNA_SALDO_EMP_X(param list change)  */
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))
 AS
 BEGIN SUSPEND; END
^

/*  Empty VSUC_SP_RETORNA_MOV_DIARIO for SP_RETORNA_SALDO_EMP_X(param list change)  */
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 VSUC_SP_RETORNA_MOV_MENSAL for SP_RETORNA_SALDO_EMP_X(param list change)  */
ALTER PROCEDURE VSUC_SP_RETORNA_MOV_MENSAL(PRCODEMP INTEGER,
PRCONTA INTEGER,
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 VSUC_SP_RETORNA_RAZAO_SALDO_X for SP_RETORNA_SALDO_EMP_X(param list change)  */
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,
PRDETALHARCC INTEGER,
PRLCC VARCHAR(1024),
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,
PRDETALHARFILIAL INTEGER,
PRDCDOISLANCAMENTOS INTEGER,
PRIGNORAZERAMENTO INTEGER = 0,
PRIGNORASALDOANTERIOR 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),
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,
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))
 AS
 BEGIN SUSPEND; END
^

/*  Empty VSUC_SP_BALANCETE_MENSAL for VSUC_SP_RETORNA_BALANCETE(param list change)  */
ALTER PROCEDURE VSUC_SP_BALANCETE_MENSAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN 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
^

/*  Empty VSUC_SP_BALANCO_PATRIMONIAL for VSUC_SP_RETORNA_SALDO_CONTAS_X(param list change)  */
ALTER PROCEDURE VSUC_SP_BALANCO_PATRIMONIAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSEMCC INTEGER)
 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 VSUC_SP_RETORNA_BALANCETE for VSUC_SP_RETORNA_SALDO_CONTAS_X(param list change)  */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN 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)
 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))
 AS
 BEGIN SUSPEND; END
^

/*  Empty VSUC_SP_RETORNA_BALANCO_PATRIMO for VSUC_SP_RETORNA_SALDO_CONTAS_X(param list change)  */
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),
PRLISTACC VARCHAR(2048),
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 */ 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
^

/*  Empty VSUC_SP_RETORNA_REL_ORCA for VSUC_SP_RETORNA_SALDO_ORCA(param list change)  */
ALTER PROCEDURE VSUC_SP_RETORNA_REL_ORCA(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN 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
^

/*  Empty VSUC_SP_LISTA_CTA_RAZAO_VIDEO for VSUC_SP_RETORNA_SALDOS_CTAPARTY(param list change)  */
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 VSUC_SP_RETORNA_COMPARATIVO for VSUC_SP_RETORNA_SALDOS_CTAPARTY(param list change)  */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO(PREMPRESAS VARCHAR(1024),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
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
^

/*  Empty VSUC_SP_RETORNA_RAZAO_SALDO2 for VSUC_SP_RETORNA_SALDOS_CTAPARTY(param list change)  */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO2(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,
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 empty procedure SP_RETORNA_EMPRESA_FILIAIS with new param-list */
ALTER PROCEDURE SP_RETORNA_EMPRESA_FILIAIS(PRCODEMP INTEGER,
PRREFEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter empty procedure SP_RETORNA_SALDO_EMP_X with new param-list */
ALTER PROCEDURE SP_RETORNA_SALDO_EMP_X(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRINDICE INTEGER,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0,
PRPARTICIPANTEFINAL 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
 BEGIN SUSPEND; END
^

/* Alter empty procedure VSUC_SP_RETORNA_BALANCETE with new param-list */
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)
 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))
 AS
 BEGIN SUSPEND; END
^

/* Alter empty procedure VSUC_SP_RETORNA_SALDO_CONTAS_X with new param-list */
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)
 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
^

/* Alter empty procedure VSUC_SP_RETORNA_SALDO_CONTAS_XZ with new param-list */
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
 BEGIN SUSPEND; END
^

/* Alter empty procedure VSUC_SP_RETORNA_SALDO_ORCA with new param-list */
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 empty procedure VSUC_SP_RETORNA_SALDOS_CTAPARTY with new param-list */
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)
 AS
 BEGIN SUSPEND; END
^

/* Alter Procedure... */
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
^

/* 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 INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0,
PRPARTICIPANTEFINAL 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 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;
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);
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 NAO CONCILIADOS

  -- 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,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     BEGIN
       --wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA ';
       --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(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
       --alt:6178 - Fim

       wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
       IF (prignorazeramento = 1) THEN
          wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

       --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||') 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:6178 - Fim

       wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC, planos_tpla TPLA ';
       wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     BEGIN
       --wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';
       --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(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
       --alt:6178 - Fim

       wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
       IF (prignorazeramento = 1) THEN
          wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

       --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||') 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:6178 - Fim

       wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN, planos_tpla TPLA ';
     END

  wsql = wsql||' where TPLA.BDCTALON like ''' || wclassificacao || '%''';
  wsql = wsql||' and tpla.bdcodplapadrao=' || wcodplapadrao;
  wsql = wsql||' and';
  wsql = wsql||' (';
  wsql = wsql||'   (tpla.bdtipcta = 1)';
  wsql = wsql||'   or';
  wsql = wsql||'   (tpla.bdtipcta is null)';
  wsql = wsql||' )';

  IF (prrelcta IS NOT NULL) THEN
    wsql = wsql||' and tpla.bdrelcta = '||prrelcta||' ';

  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||' and tlan.bdcontabilizacao in (0,'||prcontabilizacao||') ';

  EXECUTE PROCEDURE CONTAR_CHAR(wclassificacao, '.') RETURNING_VALUES :wNivel;
  wsql = wsql||' and tpla.bdnivel >= ' || wNivel;

  wsql = wsql||' and TPLA.bdcodtpla = tlan.bddebito';
  wsql = wsql||' and TLAN.BDDATA <= '''||wdatfin||''' ';
  wsql = wsql||' and tlan.bdcodplapadrao = '||wcodplapadrao;

  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,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     BEGIN
       --wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA ';
       --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(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
       --alt:6178 - Fim

       wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
       IF (prignorazeramento = 1) THEN
          wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

       --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||') 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:6178 - Fim

       wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC, planos_tpla TPLA ';
       wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     BEGIN
       --wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';
       --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(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
       --alt:6178 - Fim

       wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
       IF (prignorazeramento = 1) THEN
          wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

       --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||') 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:6178 - Fim

       wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN, planos_tpla TPLA ';
     END

  wsql = wsql||' where TPLA.BDCTALON like ''' || wclassificacao || '%''';
  wsql = wsql||' and tpla.bdcodplapadrao=' || wcodplapadrao;
  wsql = wsql||' and';
  wsql = wsql||' (';
  wsql = wsql||'   (tpla.bdtipcta = 1)';
  wsql = wsql||'   or';
  wsql = wsql||'   (tpla.bdtipcta is null)';
  wsql = wsql||' )';

  IF (prrelcta IS NOT NULL) THEN
    wsql = wsql||' and tpla.bdrelcta = '||prrelcta||' ';

  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||' and tlan.bdcontabilizacao in (0,'||prcontabilizacao||') ';

  EXECUTE PROCEDURE CONTAR_CHAR(wclassificacao, '.') RETURNING_VALUES :wNivel;
  wsql = wsql||' and tpla.bdnivel >= ' || wNivel;

  wsql = wsql||' and TPLA.bdcodtpla = tlan.bdcredito';
  wsql = wsql||' and TLAN.BDDATA <= '''||wdatfin||''' ';
  wsql = wsql||' and tlan.bdcodplapadrao = '||wcodplapadrao;

  wParte = wsql;
  wgroupby = ' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';

  wsql = wparte;
  --#Alt:10551. Carlos Mello  bdTIPOLANCFILIAL -> 0 – Nenhum | 1 – Débito | 2 - Crédito
  --wsql = wsql||' and (tlan.bdcodemp = '||prcodemp||' and tlan.bdtipolancfilial <> 1) ';
  wsql = wsql||' and (tlan.bdcodemp = '||prcodemp||' and tlan.bdtipolancfilial <> 2) ';
  wsql = wsql||wgroupby;

  wsql = wsql || ' union all ';
  wsql = wsql || wparte;
  --#Alt:10551. Carlos Mello  bdTIPOLANCFILIAL -> 0 – Nenhum | 1 – Débito | 2 - Crédito
  --wsql = wsql || ' and (tlan.bdfilial = '||prcodemp||' and tlan.bdtipolancfilial = 1) ';
  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_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 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_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))
 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 from tempresas emp ';
  wsql2 = wsql2||'left outer join VW_EMPRESAS_REF_ATUAL ref on (ref.bdcodemp = emp.bdcodemp) ';
  wsql2 = wsql2||'where '||:PRCODEMP;

  FOR EXECUTE STATEMENT wSQL2 INTO :bdcodemp, :bdcodmatriz, :WPLANOCONTAS 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, 0, 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, 0, 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, 0, 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, 0, 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, 0, NULL, :PRREFEMP, 0, 1, 0)
          INTO :bdSALDO;
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END
    END

  --suspend;
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))
 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;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, 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,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;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :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 (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    wCCNull = 0;
    IF ((wccatu IS NULL) ) THEN                --AND (wcc IS NOT NULL)
       wccnull = 1;
    IF ((wcc IS NULL)) THEN                 --(wccatu IS NOT NULL) AND 
       wccnull = 1;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1)) 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;


         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;
     
              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;
       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
         )
         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, 7, 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
       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'))) 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, 7, 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
            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) 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;

       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;
     
            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 (VSUC_GETDEMONSTRATIVO) */
ALTER PROCEDURE VSUC_GETDEMONSTRATIVO(PRCODEMP VARCHAR(1000),
PRIGNORAZERAMENTO INTEGER,
PRDETALHAFILIAL INTEGER,
PRCONTABILIZACAO INTEGER,
PRDATAINI DATE,
PRDATAFIN DATE,
PREXPORTACAOECF INTEGER,
PRINDICE 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))
 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 WANOECF SMALLINT;
BEGIN
  -- 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||'(((bdcodemp = '||wcodmatriz||')';
      IF (wcodmatriz <> SUBSTRING(wstr FROM 1 FOR wcount-1)) THEN
         wempresas = wempresas||' and (bdfilial = '||SUBSTRING(wstr FROM 1 FOR wcount-1)||')) or (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 padrão
  --alt:11615 - 30/06/2015 - Carrega o código 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 preparação mais próximo 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
            wdataini_ant = wdataini;
            wdatafin_ant = wdatafin;
            wzeramento_ant = 1;
          END
       ELSE
          BEGIN
            wdataini_ant_ant = wdataini;
            wdatafin_ant_ant = wdatafin;
            wzeramento_ant_ant = 1;
          END
       wcount = wcount + 1;
     END
  -- caso não há 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 período anterior
  IF ((wdataini_ant IS NULL) OR (wdatafin_ant IS NULL)) THEN
     BEGIN
       wdataini_ant = wdataini;
       wdatafin_ant = prdataini -1;
     END
  -- data do período 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 temporária
  EXECUTE STATEMENT 'delete from VSUC_EMPRESAS_DEMONSTRATIVO';

  -- calculo dos debitos e creditos nos períodos selecionados
  wsqldeb = '';
  -- saldo anterior a todos os períodos
  wsqldeb = wsqldeb||'sum(case when (bddata < '''||wdataini_ant_ant||''') then coalesce(bdvalor, 0) else 0 end) as bddebitoantzer, ';
  wsqldeb = wsqldeb||'sum(case when (bddata < '''||wdataini_ant_ant||''' and bdtipolan <> 10) then coalesce(bdvalor, 0) else 0 end) as bddebitoant, ';
  -- período anterior ao anterior
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini_ant_ant||''' and '''||wdatafin_ant_ant||''') then coalesce(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(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(bdvalor, 0) else 0 end) as bddebito2atu, ';
  -- periodo anterior
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini_ant||''' and '''||wdatafin_ant||''') then coalesce(bdvalor, 0) else 0 end) as bddebito1zer, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini_ant||''' and '''||wdatafin_ant||''') and (bdtipolan <> 10)) then coalesce(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(bdvalor, 0) else 0 end) as bddebito1atu, ';
  -- periodo atual
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini||''' and '''||wdatafin||''') then coalesce(bdvalor, 0) else 0 end) as bddebitozer, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini||''' and '''||wdatafin||''') and (bdtipolan <> 10)) then coalesce(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(bdvalor, 0) else 0 end) as bddebitoatu ';
  --exception ex_date;

  --alt:6178 - 11/11/2015 - Adicionada validação, se tiver informado um código de índice, então substituirá onde possui o campo "BDVALOR" pelo próprio campo mais o valor do índice na data do lançamento. Pedro
  if (prIndice > 0) then
    wsqldeb = replace(wsqldeb, 'bdvalor', '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))');

  wsqlcre = '';
  -- saldo anterior a todos os períodos
  wsqlcre = wsqlcre||'       0 as bdcreditoantzer, ';
  wsqlcre = wsqlcre||'       0 as bdcreditoant, ';
  -- período 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 temporária
  wsql = 'insert into VSUC_EMPRESAS_DEMONSTRATIVO (';
  wsql = wsql||'bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla, ';
  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, ';
  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 (';
  wsql = wsql||'select bdcodemp, bdfilial, bdtipolancfilial, bddebito as bdcodtpla, ';
  wsql = wsql||wsqldeb||','||wsqlcre;
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  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 bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla ';
  wsql = wsql||'union ';
  wsql = wsql||'select bdcodemp, bdfilial, bdtipolancfilial, bdcredito as bdcodtpla, ';
  wsql = wsql||wsqlcre||','||wsqldeb;
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  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 ';
  wsql = wsql||') ';
  wsql = wsql||'group by bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla ';
  wsql = wsql||'order by bdcodemp, bdcodtpla ';
  EXECUTE STATEMENT wsql;

  -- inserir contas títulos e totalizando-as
  FOR SELECT bdcodtpla, bdctalon FROM planos_tpla
      WHERE bdcodplapadrao = :bdcodplapadrao
      AND bdtipcta = 0
      INTO :wcodtpla, :wctalon DO
      BEGIN
        wsql = 'insert into VSUC_EMPRESAS_DEMONSTRATIVO (bdcodemp, bdtipolancfilial, bdcodtpla, ';
        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||'       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 ';
        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 exportação 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 ';
     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 exportação 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) ';
     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 exportação 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
  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 ';
       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 DO
      BEGIN
        IF (bdgrupocta IN (1,2,3)) THEN
           BEGIN-- credito - debito
             bdsalant2 = wcre_ant - wdeb_ant;
             bdsaldeb2 = wdeb_2;
             bdsalcre2 = wcre_2;
             --#alt:7476. Não estava respeitando a natureza da conta(Credora/Devedora)
             --bdmovper2 = abs(wcre_2 - wdeb_2);
             bdmovper2 = (wcre_2 - wdeb_2);
--             bdsalatu2 = (wcre_ant_zer - wdeb_ant_zer) + (wcre_2 - wdeb_2);
             bdsalatu2 = (wcre_2_atu - wdeb_2_atu);

             bdsalant1 = bdsalatu2;
             bdsaldeb1 = wdeb_1;
             bdsalcre1 = wcre_1;
             --#alt:7476. Não estava respeitando a natureza da conta(Credora/Devedora)
             --bdmovper1 = abs(wcre_1 - wdeb_1);
             bdmovper1 = (wcre_1 - wdeb_1);
--             bdsalatu1 = (wcre_ant_zer - wdeb_ant_zer) + (wcre_1_zer - wdeb_1_zer) + (wcre_1 - wdeb_1);
/*             bdsalatu1 = (wcre_ant_zer - wdeb_ant_zer);
             if (wzeramento_ant = 1) then
                bdsalatu1 = bdsalatu1 + (wcre_1_zer - wdeb_1_zer);
             bdsalatu1 = bdsalatu1 + (wcre_1 - wdeb_1);*/
             bdsalatu1 = (wcre_1_atu - wdeb_1_atu);

             bdsalant = bdsalatu1;
             IF ((prignorazeramento = 0) or (wCodPlaPadraoRef = 4)) THEN --alt:11615 - 30/06/2015 - Verifica o grupo da conta preparada no Sped ECF, o grupo 04 deverá ignorar o zeramento. Pedro
                BEGIN
                  bdsaldeb = wdeb;
                  bdsalcre = wcre;
                  --#alt:7476. Não estava respeitando a natureza da conta(Credora/Devedora)
                  --bdmovper = abs(wcre - wdeb);
                  bdmovper = (wcre - wdeb);
--                  bdsalatu = (wcre_ant_zer - wdeb_ant_zer) + (wcre_1_zer - wdeb_1_zer) + (wcre_2_zer - wdeb_2_zer) + (wcre - wdeb);
                  bdsalatu = (wcre_atu - wdeb_atu);
                END
             ELSE
                BEGIN
                  bdsaldeb = wdeb_zer;
                  bdsalcre = wcre_zer;
                  --#alt:7476. Não estava respeitando a natureza da conta(Credora/Devedora)
                  --bdmovper = abs(wcre_zer - wdeb_zer);
                  bdmovper = (wcre_zer - wdeb_zer);
--                  bdsalatu = (wcre_ant_zer - wdeb_ant_zer) + (wcre_1_zer - wdeb_1_zer) + (wcre_2_zer - wdeb_2_zer) + (wcre_zer - wdeb_zer);

                  --alt:11029 - 23/03/2015 - Alterada a variável para pegar a do zeramento. Pedro
                  --bdsalatu = (wcre_atu - wdeb_atu);
                  bdsalatu = (wcre_zer - wdeb_zer) + bdsalant;
                END
           END
        ELSE
           BEGIN-- debito - credito
             bdsalant2 = wdeb_ant - wcre_ant;
             bdsaldeb2 = wdeb_2;
             bdsalcre2 = wcre_2;
             --#alt:7476. Não estava respeitando a natureza da conta(Credora/Devedora)
             --bdmovper2 = abs(wdeb_2 - wcre_2);
             bdmovper2 = (wdeb_2 - wcre_2);
--             bdsalatu2 = (wdeb_ant_zer - wcre_ant_zer) + (wdeb_2 - wcre_2);
             bdsalatu2 = (wdeb_2_atu - wcre_2_atu);

             bdsalant1 = bdsalatu2;
             bdsaldeb1 = wdeb_1;
             bdsalcre1 = wcre_1;
             --#alt:7476. Não estava respeitando a natureza da conta(Credora/Devedora)
             --bdmovper1 = abs(wdeb_1 - wcre_1);
             bdmovper1 = (wdeb_1 - wcre_1);
--             bdsalatu1 = (wdeb_ant_zer - wcre_ant_zer) + (wdeb_1_zer - wcre_1_zer) + (wdeb_1 - wcre_1);
/*             bdsalatu1 = (wdeb_ant_zer - wcre_ant_zer);
             if (wzeramento_ant = 1) then
                bdsalatu1 = bdsalatu1 + (wdeb_1_zer - wcre_1_zer);
             bdsalatu1 = bdsalatu1 + (wdeb_1 - wcre_1);*/
             bdsalatu1 = (wdeb_1_atu - wcre_1_atu);

             bdsalant = bdsalatu1;
             IF ((prignorazeramento = 0) or (wCodPlaPadraoRef = 4)) THEN --alt:11615 - 30/06/2015 - Verifica o grupo da conta preparada no Sped ECF, o grupo 04 deverá ignorar o zeramento. Pedro
                BEGIN
                  bdsaldeb = wdeb;
                  bdsalcre = wcre;
                  --#alt:7476. Não estava respeitando a natureza da conta(Credora/Devedora)
                  --bdmovper = abs(wdeb - wcre);
                  bdmovper = (wdeb - wcre);
--                  bdsalatu = (wdeb_ant_zer - wcre_ant_zer) + (wdeb_1_zer - wcre_1_zer) + (wdeb_2_zer - wcre_2_zer) + (wdeb - wcre);
                  bdsalatu = (wdeb_atu - wcre_atu);
                END
             ELSE
                BEGIN
                  bdsaldeb = wdeb_zer;
                  bdsalcre = wcre_zer;
                  --#alt:7476. Não estava respeitando a natureza da conta(Credora/Devedora)
                  --bdmovper = abs(wdeb_zer - wcre_zer);
                  bdmovper = (wdeb_zer - wcre_zer);
--                  bdsalatu = (wdeb_ant_zer - wcre_ant_zer) + (wdeb_1_zer - wcre_1_zer) + (wdeb_2_zer - wcre_2_zer) + (wdeb_zer - wcre_zer);

                  --alt:11029 - 23/03/2015 - Alterada a variável para pegar a do zeramento. Pedro
                  --bdsalatu = (wdeb_atu - wcre_atu);
                  bdsalatu = (wdeb_zer - wcre_zer) + bdsalant;
                END
           END

        SUSPEND;
      END
END
^

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)
 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))
 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);
BEGIN
/*
                   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.bdcodparticipante
--                           from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           from vsuc_sp_retorna_saldos_ctaparty(2027,9019,'01/01/2013','12/31/2013',432,
                                                                0,0,0,0,'2027',1,0) tsalctapar
                       into :bdnomcta, :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :wcodparticipante do
                       begin
                         suspend;
                       end

  wconta = 5000;
  while (wconta > 0) do
    wconta = wconta - 1;
  exit;
*/

-- 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;
        -- delete from vsuc_empresas_tbalancete where bdcodemp <> 0;
        -- 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.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,0,
                                                     :prnaomostracontacomp,:prconsolidada,:prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,:prdre) 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
                           --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 DO
                           BEGIN

                             bdcodter = :wcodparticipante;
                             bdclanom = SUBSTRING(bdctalon FROM 1 FOR strlen(bdctalon)-10)||' '||bdnomcta;
/* gilberto - 21/01/2014 - alt#7580 - não há nescessidade de concatenar o código do participante ao nome
                             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
*/

--                             select first 1 bdnometer from tterceiro_ref where bdcodter = coalesce(cast(substring(:bdctalon from strlen(:bdctalon)-8 for 9) as integer), 0) order by bdrefemp desc into :bdnomcta;
                             -- gilberto - 20/01/2014 - subiu para antes de alterar "bdnomcta" para ordem alfabetica não usar concatenação com o código de participante
                             --bdclanom = substring(bdctalon from 1 for strlen(bdctalon)-10)||' '||bdnomcta;



                             -- Carlos Mello(05/06/2012) - Solicitação.: 3424.
--                             bdclanom = (select bdretorno from preenche_direita(substring(:bdctalon from 1 for (select BDRPOS from RPOS('.',:bdctalon)) - 1),20,' ')) ||' ' || :bdnomcta;
/*
--                             insert into vsuc_empresas_tbalancete_2 (bddatahora, bdcodemp, bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
                             insert into vsuc_empresas_tbalancete_3 (bdcodemp, bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
                                                                     bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdrelcta, bdclanom, bdformula, bdparticipante, bdapecta)
--                             values(:wdatahora, :bdcodempfilial, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdtipcta, :bdgrpcta, :bdnomcta, :bdsaldo_deb,
                             values(:bdcodempfilial, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdtipcta, :bdgrpcta, :bdnomcta, :bdsaldo_deb,
                                    :bdsaldo_cre, :bdsaldo_ant_deb, :bdsaldo_ant_cre, :bdrelcta, :bdclanom, :bdformula, :wparticipante, :bdapecta);

                             bdmovimento = bdsaldo_atual - bdsaldo_anterior;*/
                             SUSPEND;
                           END

                     END
                   ELSE
                     BEGIN
                       bdcodter = 0;
                       bdmovimento = bdsaldo_atual - bdsaldo_anterior;

                       --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 ((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 <> '')) THEN
                           BEGIN
                             SUSPEND;
                           END

                       -- 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
             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;
             -- 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||')';*/

             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;

                         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)) 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: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)) THEN
                   SUSPEND;
             --alt:9386 - Fim

             -- execucao do sql por centro de custo para trazer os lançamentos sem o centro de custo
             /*if (prlansemcc = 1) then
                begin

                  bdcodtpcc = 0;
                  bdnomtpcc = '';
                  bdtpcclon = '';

                  -- retorna todas as contas do plano de contas sem o centro de custo
                  -- nova rotina abaixo, giovanni
                  for select conta, classificacao, nomeconta, tipconta, GRUPOCONTA,
                             saldo_ant_deb, saldo_ant_cre, saldo_deb,
                             saldo_cre, saldo_atual,
                             saldo_anterior, formula, relconta, clanom, formula, apecta,
                             saldo_ant_deb_dre, saldo_ant_cre_dre, saldo_anterior_dre
                             from vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prignora_zeramento, 0,
                                                                 :bdcodplapadrao,1,:prnaomostracontacomp,:prconsolidada,:prniveisconta,:prcodemp,
                                                                 :prcontabilizacao,:prmatrizfilialconsolidado,:prdre) tsalcta
                             --                 where ((tsalcta.relconta = 0) or (tsalcta.relconta is null))
                            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 do
                      begin
                              if (wctalonant <> wctalon) then
                                 begin
                                   bdcodtpcc = null;
                                   bdnomtpcc = 'Sem Centro de Custo';
                                   bdtpcclon = null;
                                   bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                                   -- gilberto
                                   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)) then
                                       begin
                                         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

                                   bdcodcta  = wconta;
                                   bdctalon  = wctalon;
                                   bdnomcta  = wnomcta;
                                   bdtipcta  = wtipcta;
                                   bdclanom  = wclanom;
                                   bdgrpcta  = wgrpcta;
                                   bdformula = wformula;
     
                                   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;

                                   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;
                                   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;

                                   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;
                      end
                end


             -- execucao do sql por centro de custo
             for execute statement wsql
                 into :bdcodtpcc, :bdnomtpcc, :bdtpcclon do
                 begin
                   delete from vsuc_empresas_tbalancete_3 where bdcodemp <> 0;-- alt:#6976 - gilberto - 24/10/2013 - misturava CC
                   -- laco que retorna as contas por centro de custo selecionado
                   for select conta, classificacao, nomeconta, tipconta, GRUPOCONTA,
                              saldo_ant_deb, saldo_ant_cre, saldo_deb, saldo_cre, saldo_atual,
                              saldo_anterior, formula, relconta, clanom, apecta,
                              saldo_ant_deb, saldo_ant_cre, saldo_anterior
                       from vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prignora_zeramento, :bdcodtpcc,
                                                           :bdcodplapadrao,0,:prnaomostracontacomp,:prconsolidada,:prniveisconta,:prcodemp,:prcontabilizacao,
                                                           :prmatrizfilialconsolidado,:prdre)
                       into :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta,
                            :wsaldo_ant_deb, :wsaldo_ant_cre, :wsaldo_deb, :wsaldo_cre, :wsaldo_atual,
                            :wsaldo_anterior, :wformula, :bdrelcta, :wclanom, :bdapecta,
                            :wsaldo_ant_deb_dre, :wsaldo_ant_cre_dre, :wsaldo_anterior_dre do
                       begin
                         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)) then
                             begin
                               if (wctalonant <> wctalon) then
                                  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

                              bdcodcta  = wconta;
                              bdctalon  = wctalon;
                              bdnomcta  = wnomcta;
                              bdtipcta  = wtipcta;
                              bdclanom  = wclanom;
                              bdgrpcta  = wgrpcta;
                              bdformula = wformula;

                              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;

                              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;
                              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;

                              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;
                       end
                 end*/
           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_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 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)
 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 ';
      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)),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 ';
      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 ';
    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

      --alt:10233 - Retirada essa validação daqui, implementado mais abaixo porque validando aqui ele não consegue saber qual a conta que está sendo calculada (débito ou crédito). Pedro
      --alt:9527 - Adicionado left outer join na tabela de contas para saber se é uma conta de compensação. Pedro
      /*if (prnaomostracontacomp = 0) then
        begin
          wsql = wsql||'left outer join PLANOS_TPLA tpla1 on (tlan.BDCODPLAPADRAO = tpla1.BDCODPLAPADRAO and tlan.BDDEBITO = tpla1.BDCODTPLA) ';
          wsql = wsql||'left outer join PLANOS_TPLA tpla2 on (tlan.BDCODPLAPADRAO = tpla2.BDCODPLAPADRAO and tlan.BDCREDITO = tpla2.BDCODTPLA) ';
        end*/
      --alt:9527 - Fim

      wsql = wsql||'where (tlan.bddata <= '''||prdatafim||''') ';

      --alt:10233 - Retirada essa validação daqui, implementado mais abaixo porque validando aqui ele não consegue saber qual a conta que está sendo calculada (débito ou crédito). Pedro
      --alt:9527 - Adicionado para quando for o caso de não imprimir contas de compensação. Pedro
      /*if (prnaomostracontacomp = 0) then
        begin
          wsql = wsql||'and ((tpla1.BDCTACOMP is null) or (tpla1.BDCTACOMP = '''||'FALSE'||''')) ';
          wsql = wsql||'and ((tpla2.BDCTACOMP is null) or (tpla2.BDCTACOMP = '''||'FALSE'||''')) ';
        end*/
      --alt:9527 - Fim

      --#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 = 0) THEN --alt:11108 - 08/04/2015 - Invertido parâmetro para ficar correto. 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 = 0) THEN --alt:11108 - 08/04/2015 - Invertido parâmetro para ficar correto. Pedro
    wsql = wsql||'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';

  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 = 0) THEN --alt:11108 - 08/04/2015 - Invertido parâmetro para ficar correto. 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 = 0) THEN --alt:11108 - 08/04/2015 - Invertido parâmetro para ficar correto. Pedro
    wsql = wsql||'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';

  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
     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 <> '''||''||'''))) ';
       --alt:9527 - Trocado de 1 para 0 a pedido da solicitação, para acertar a concordância com o descrito no campo. Pedro
       IF (prnaomostracontacomp = 0) 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 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)
 AS
declare variable WGRUPOCTA integer;
declare variable WSQL varchar(10000);
declare variable WSQL_AUX varchar(10000);
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 WCODPARTICIPANTE integer;
declare variable WCNPJPART varchar(10);
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);
BEGIN
/*
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: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, bdcodtpla, tlan.bdcodter, terc.bdnometer, ';
  --wsql = 'select bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla, tlan.bdcodter, null as bdnometer, ';
  wsql = 'select bdcodemp, bdfilial, bdtipolancfilial, tlan.bdcodtpla, tlan.bdcodter, substring(bdcgcter from 1 for 10) as bdcnpjparticipante, ';
  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.bdcodemp in ('||prempresas||')) or (tlan.bdfilial = '||prcodemp||')) ';----
  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||'))';

  --alt:7823 - Estava jogando parte do filtro em uma variável nunca utilizada e trazendo o resultado incorreto. Foi trocado de 'wsql_aux' para 'wsql'. Pedro
  IF (prconciliados = 1) THEN
     wsql = wsql||' and (upper(tlan.bdconcd) = '''||'TRUE'||''') ';
     --wsql_aux = wsql_aux||' and (upper(tlan.bdconcd) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
     wsql = wsql||' and ((tlan.bdconcd is null) or (upper(tlan.bdconcd) = '''||'FALSE'||''')) ';
     --wsql_aux = wsql_aux||' and ((tlan.bdconcd is null) or (upper(tlan.bdconcd) = '''||'FALSE'||''')) ';
  --alt:7823 - Fim

--  wsql = wsql||'and ((tlan.bdcodemp in ('||prempresas||')) or (tlan.bdfilial = '||prcodemp||')) ';----

  wsql = wsql||' and (';
  wempresas = prempresas||',';
  wor = '';
  WHILE (wempresas <> '') DO
    BEGIN
      wpos = POSITION(',', wempresas);
      IF (SUBSTRING(wempresas FROM 1 FOR wpos-1) <> prcodemp) THEN
         BEGIN
           wsql = wsql||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 = wsql||' or (bdcodemp = '||prcodemp||')';
   ELSE
      wsql = wsql||'(bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')';
   wsql = wsql||') ';


  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.bdcodemp in ('||prempresas||')) or (tlan.bdfilial = '||prcodemp||')) ';----
  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||'and ((tlan.bdcodemp in ('||prempresas||')) or (tlan.bdfilial = '||prcodemp||')) ';----

  wsql = wsql||' and (';
  wempresas = prempresas||',';
  wor = '';
  WHILE (wempresas <> '') DO
    BEGIN
      wpos = POSITION(',', wempresas);
      IF (SUBSTRING(wempresas FROM 1 FOR wpos-1) <> prcodemp) THEN
         BEGIN
           wsql = wsql||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 = wsql||' or (bdcodemp = '||prcodemp||')';
   ELSE
      wsql = wsql||'(bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')';
   wsql = wsql||') ';



  wsql = wsql||'group by tlan.bdcodemp, tlan.bdfilial, tlan.bdcodplapadrao, tlan.bdtipolancfilial, tlan.bddata, tlan.bdcredito, tlan.bdcodterceiroc, tlan.bdtipolan ';
  ------------------------------------------------------------------------------
  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||'            where RF.bdREFEMP <= 201309) terc on (terc.bdcodter = tlan.bdcodter) ';
--  wsql = wsql||'group by bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla, bdcodter, bdnometer ';

  --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 ';
  wsql = wsql||'group by bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla, bdcodter, bdcnpjparticipante ';

  --alt:9167 - Alterado order, deve primeiro ordenar pelo CNPJ para trazer juntas as mesmas empresas. Pedro
  --wsql = wsql||'order by bdcodter';
  wsql = wsql||'order by bdcnpjparticipante, bdcodter desc ';

  FOR EXECUTE STATEMENT wsql
  --alt:9167 - Trocados campos de retorno da consulta. Pedro
  --into :wcodemp, :wfilial, :wtipolancfilial, :wcodtpla, :bdcodparticipante, :bdnome, :bdsaldo_ant_deb, :bdsaldo_deb, :bdsaldo_ant_cre, :bdsaldo_cre do
  INTO :wcodemp, :wfilial, :wtipolancfilial, :wcodtpla, :wcodparticipante, :wcnpjpart, /*:wnome,*/ :wsaldo_ant_deb, :wsaldo_deb, :wsaldo_ant_cre, :wsaldo_cre DO
  BEGIN
     --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 do primeiro participante pelo código. Pedro
     IF ((pragruparparticipanteporcnpj = 0) AND (wcnpjantpart IS NULL)) THEN
       SELECT FIRST 1 SUBSTRING(BDCGCTER FROM 1 FOR 10) FROM TTERCEIRO WHERE BDCODTER = :wcodparticipante INTO :wcnpjantpart;

     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)
           ((wcodemp = wfilial) AND (wtipolancfilial NOT IN (1,2))) 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 (wtipolancfilial NOT IN (1,2)) 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 (wtipolancfilial NOT IN (1,2)) AND (wpos_filial > 0))) THEN
          wpermite = 1;
       ELSE
       IF ((wcodemp <> wfilial) AND (wcodemp <> prcodemp) AND (wtipolancfilial IN (1,2))) 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
         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;
           end
         bdclassificacao = substring(wclassificacao from 1 for wposant)||lpad(bdcodparticipante, 8, '0');
         select first 1 bdnometer from tterceiro_ref where bdcodter = :bdcodparticipante order by bdrefemp desc into :bdnome;

         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*/

    --alt:9167 - Novo método de retorno dos valores. Pedro
    IF (wpermite = 1) THEN
       BEGIN
         --Quando não está agrupando por CNPJ.
         IF (pragruparparticipanteporcnpj = 0) THEN
           BEGIN
             wpos = 1;
             wposant = 0;
             bdcodparticipante = wcodparticipante;
             bdclassificacao = wclassificacao;
             WHILE (POSITION('.', bdclassificacao) > 0) DO
               BEGIN
                 wpos = wpos + POSITION('.', bdclassificacao);
                 bdclassificacao = SUBSTRING(wclassificacao FROM wpos FOR strlen(wclassificacao));
                 wposant = wpos;
               END
             bdclassificacao = SUBSTRING(wclassificacao FROM 1 FOR wposant)||LPAD(wcodparticipante, 8, '0');
             SELECT FIRST 1 bdnometer FROM tterceiro_ref WHERE bdcodter = :wcodparticipante ORDER BY bdrefemp DESC INTO :bdnome;

             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

             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
             SUSPEND;

             wpos = 1;
             wposant = 0;
             bdcodparticipante = wcodparticipante;
             bdclassificacao = wclassificacao;
             WHILE (POSITION('.', bdclassificacao) > 0) DO
               BEGIN
                 wpos = wpos + POSITION('.', bdclassificacao);
                 bdclassificacao = SUBSTRING(wclassificacao FROM wpos FOR strlen(wclassificacao));
                 wposant = wpos;
               END
             bdclassificacao = SUBSTRING(wclassificacao FROM 1 FOR wposant)||LPAD(wcodparticipante, 8, '0');
             SELECT FIRST 1 bdnometer FROM tterceiro_ref WHERE bdcodter = :wcodparticipante ORDER BY bdcodter desc, bdrefemp DESC INTO :bdnome;

             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
           END
         --O CNPJ atual é igual ao anterior (mesma empresa, então deve agrupar).
         ELSE
           BEGIN
             wpos = 1;
             wposant = 0;
             bdcodparticipante = wcodparticipante;
             bdclassificacao = wclassificacao;
             WHILE (POSITION('.', bdclassificacao) > 0) DO
               BEGIN
                 wpos = wpos + POSITION('.', bdclassificacao);
                 bdclassificacao = SUBSTRING(wclassificacao FROM wpos FOR strlen(wclassificacao));
                 wposant = wpos;
               END
             bdclassificacao = SUBSTRING(wclassificacao FROM 1 FOR wposant)||LPAD(wcodparticipante, 8, '0');
             SELECT FIRST 1 bdnometer FROM tterceiro_ref WHERE bdcodter = :wcodparticipante ORDER BY bdcodter desc, bdrefemp DESC INTO :bdnome;

             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
           END
         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
     ((COALESCE(bdsaldo_ant_deb, 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 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 ';

      --alt:10233 - Retirada essa validação daqui, implementado mais abaixo porque validando aqui ele não consegue saber qual a conta que está sendo calculada (débito ou crédito). Pedro
      --alt:9527 - Adicionado left outer join na tabela de contas para saber se é uma conta de compensação. Pedro
      /*if (prnaomostracontacomp = 0) then
        begin
          wsql = wsql||'left outer join PLANOS_TPLA tpla1 on (tlan.BDCODPLAPADRAO = tpla1.BDCODPLAPADRAO and tlan.BDDEBITO = tpla1.BDCODTPLA) ';
          wsql = wsql||'left outer join PLANOS_TPLA tpla2 on (tlan.BDCODPLAPADRAO = tpla2.BDCODPLAPADRAO and tlan.BDCREDITO = tpla2.BDCODTPLA) ';
        end*/
      --alt:9527 - Fim

      wsql = wsql||wsql_aux;

      --alt:10233 - Retirada essa validação daqui, implementado mais abaixo porque validando aqui ele não consegue saber qual a conta que está sendo calculada (débito ou crédito). Pedro
      --alt:9527 - Adicionado para quando for o caso de não imprimir contas de compensação. Pedro
      /*if (prnaomostracontacomp = 0) then
        begin
          wsql = wsql||'and ((tpla1.BDCTACOMP is null) or (tpla1.BDCTACOMP = '''||'FALSE'||''')) ';
          wsql = wsql||'and ((tpla2.BDCTACOMP is null) or (tpla2.BDCTACOMP = '''||'FALSE'||''')) ';
        end*/
      --alt:9527 - Fim

      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 ';

      --alt:10233 - Retirada essa validação daqui, implementado mais abaixo porque validando aqui ele não consegue saber qual a conta que está sendo calculada (débito ou crédito). Pedro
      --alt:9527 - Adicionado left outer join na tabela de contas para saber se é uma conta de compensação. Pedro
      /*if (prnaomostracontacomp = 0) then
        begin
          wsql = wsql||'left outer join PLANOS_TPLA tpla1 on (tlan.BDCODPLAPADRAO = tpla1.BDCODPLAPADRAO and tlan.BDDEBITO = tpla1.BDCODTPLA) ';
          wsql = wsql||'left outer join PLANOS_TPLA tpla2 on (tlan.BDCODPLAPADRAO = tpla2.BDCODPLAPADRAO and tlan.BDCREDITO = tpla2.BDCODTPLA) ';
        end*/
      --alt:9527 - Fim

      wsql = wsql||wsql_aux;

      --alt:10233 - Retirada essa validação daqui, implementado mais abaixo porque validando aqui ele não consegue saber qual a conta que está sendo calculada (débito ou crédito). Pedro
      --alt:9527 - Adicionado para quando for o caso de não imprimir contas de compensação. Pedro
      /*if (prnaomostracontacomp = 0) then
        begin
          wsql = wsql||'and ((tpla1.BDCTACOMP is null) or (tpla1.BDCTACOMP = '''||'FALSE'||''')) ';
          wsql = wsql||'and ((tpla2.BDCTACOMP is null) or (tpla2.BDCTACOMP = '''||'FALSE'||''')) ';
        end*/
      --alt:9527 - Fim

      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

      --alt:10233 - Retirada essa validação daqui, implementado mais abaixo porque validando aqui ele não consegue saber qual a conta que está sendo calculada (débito ou crédito). Pedro
      --alt:9527 - Adicionado left outer join na tabela de contas para saber se é uma conta de compensação. Pedro
      /*if (prnaomostracontacomp = 0) then
        begin
          wsql = wsql||'left outer join PLANOS_TPLA tpla1 on (tlan.BDCODPLAPADRAO = tpla1.BDCODPLAPADRAO and tlan.BDDEBITO = tpla1.BDCODTPLA) ';
          wsql = wsql||'left outer join PLANOS_TPLA tpla2 on (tlan.BDCODPLAPADRAO = tpla2.BDCODPLAPADRAO and tlan.BDCREDITO = tpla2.BDCODTPLA) ';
        end*/
      --alt:9527 - Fim

      wsql = wsql||'where (tlan.bddata <= '''||prdatafim||''') ';

      --alt:10233 - Retirada essa validação daqui, implementado mais abaixo porque validando aqui ele não consegue saber qual a conta que está sendo calculada (débito ou crédito). Pedro
      --alt:9527 - Adicionado para quando for o caso de não imprimir contas de compensação. Pedro
      /*if (prnaomostracontacomp = 0) then
        begin
          wsql = wsql||'and ((tpla1.BDCTACOMP is null) or (tpla1.BDCTACOMP = '''||'FALSE'||''')) ';
          wsql = wsql||'and ((tpla2.BDCTACOMP is null) or (tpla2.BDCTACOMP = '''||'FALSE'||''')) ';
        end*/
      --alt:9527 - 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 ((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 = 0) THEN --alt:11108 - 08/04/2015 - Invertido parâmetro para ficar correto. 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 = 0) THEN --alt:11108 - 08/04/2015 - Invertido parâmetro para ficar correto. 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 = 0) THEN --alt:11108 - 08/04/2015 - Invertido parâmetro para ficar correto. 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 = 0) THEN --alt:11108 - 08/04/2015 - Invertido parâmetro para ficar correto. 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 <> '''||''||'''))) ';
            --alt:9527 - Trocado de 1 para 0 a pedido da solicitação, para acertar a concordância com o descrito no campo. Pedro
            IF (prnaomostracontacomp = 0) 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 <> '''||''||'''))) ';
       --alt:9527 - Trocado de 1 para 0 a pedido da solicitação, para acertar a concordância com o descrito no campo. Pedro
       IF (prnaomostracontacomp = 0) 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
       --FIM DO CÁLCULO DO MODELO CENTRO DE CUSTO/CONTAS
     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_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)
 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
                   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) 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
                   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) 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_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
      (((wcontaant > 0) and (wcontaant <> wcodcta)) 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)
 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
                    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) 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)
 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
  -- 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, 0, '||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, 0, '||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, 0, '||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, 0, '||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, 0, '||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, 0, '||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, 0, '||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, 0, '||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, 0, '||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, 0, '||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, 0, '||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, 0, '||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 (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
^

/* 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
             wcampo = wtipolancfilial;
             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 (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,
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,
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, NULL, 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, 0,
                                                       :prparticipante, NULL, 0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado)
                  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 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 ';*/

              wsql = wsql||'sum(TLAN.BDVALOR) AS SALDEB ';
              --alt:9515 - Fim

              wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';

              --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 bdcodemp,bdfilial,bdtipolancfilial,bdtipolan,Referencia ';
              wsql = wsql||' union all ';

              --Crédito
              wsql = wsql||'SELECT 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 ';*/

              wsql = wsql||'sum(TLAN.BDVALOR) AS SALCRE ';
              --alt:9515 - Fim

              wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';

              --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 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_X) */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS_X(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRDETALHARCC INTEGER,
PRLCC VARCHAR(1024),
PRLANCAMENTOSEMCC INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO 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),
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,
PRTIPOLANCFILIAL INTEGER,
PRTIPOLAN INTEGER,
PRCHAVEONLINE VARCHAR(120),
PRCODCENTRO INTEGER,
PRTRANSACAO INTEGER,
PRTRANFECHADA DM_BOOLEAN)
 AS
declare variable WSQL varchar(30000) character set WIN1252;
declare variable WDEBCRE integer;
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 WNOMETER varchar(100) character set WIN1252;
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;

  /* alt:12505 - 07/10/2015 - Comentadas variáveis sem uso. Pedro
  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));

  SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wselectcta;


  wsql = '';
  wsql = wsql||'select tx.bdchave, tx.bddata, ';
  wsql = wsql||'       tx.bdcodemp, emp.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||'       tx.bdconta, tx.bdcodter as bdcodter_conta, tx.bdconc as bdconc_conta, tx.bdctalon as ctalo_conta, tx.bdnomcta as bdnomcta_conta, tx.bdgrupocta as bdgrupocta_conta, tx.bdtipcta as bdtipcta_conta, tx.bdparticipante as bdparticipante_conta, ';
  wsql = wsql||'       tx.bdcontra, tx.bdcodterceiroc as bdcodter_contra, tpla.bdctalon as bdctalon_contra, tpla.bdnomcta as bdnomcta_contra, tpla.bdparticipante as bdparticipante_contra, ';
  wsql = wsql||'       tx.bddebito, tx.bdcredito, tx.debcre, ';
  wsql = wsql||'       tx.bdcodcentro, tx.bdcodtpcc, tx.bdtransacao, tx.BDTRANFECHADA, ';
  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 ';
  wsql = wsql||'from ( ';
  -- 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, tplad.bdctalon, tplad.bdnomcta, tplad.bdgrupocta, tplad.bdtipcta, ';

  --alt:7866 - 27/10/2015 - Carrega da lista se deve ou não detalhar esta conta de participante. Pedro
  if ((wselectcta is not null) and (wselectcta > 0)) then
    wsql = wsql||'     case when lista.BDTIPOSELECAO = 1 then tplad.bdparticipante else 0 end as bdparticipante, ';
  else
    wsql = wsql||'     tplad.bdparticipante, ';

  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||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
  --alt:7866 - 27/10/2015 - Pedro
  -- detalhar contas específicas de participantes ------------------------------------------------------------------------------------------------------------------------------------------------------------------
  wsql = wsql||'left join VSUC_SELECT_CONTAS lista on (tlan.BDCODPLAPADRAO = lista.BDCODPLAPADRAO and tlan.BDDEBITO = lista.BDCODTPLA) ';
  -- seleção de contas ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
     wsql = wsql||'where (tlan.bddebito in (select bdcodtpla from vsuc_select_contas tsel)) ';
  ELSE
     wsql = wsql||'where (tplad.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_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

  wsql = wsql||'and (tlan.bddata between '''||prdata_inicial||''' and '''||prdata_final||''') ';
  -- 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, tplac.bdctalon, tplac.bdnomcta, tplac.bdgrupocta, tplac.bdtipcta, ';

  --alt:7866 - 27/10/2015 - Carrega da lista se deve ou não detalhar esta conta de participante. Pedro
  if ((wselectcta is not null) and (wselectcta > 0)) then
    wsql = wsql||'     case when lista.BDTIPOSELECAO = 1 then tplac.bdparticipante else 0 end as bdparticipante, ';
  else
    wsql = wsql||'     tplac.bdparticipante, ';

  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||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
  --alt:7866 - 27/10/2015 - Pedro
  -- detalhar contas específicas de participantes ------------------------------------------------------------------------------------------------------------------------------------------------------------------
  wsql = wsql||'left join VSUC_SELECT_CONTAS lista on (tlan.BDCODPLAPADRAO = lista.BDCODPLAPADRAO and tlan.BDCREDITO = lista.BDCODTPLA) ';
  -- seleção de contas ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
     wsql = wsql||'where (tlan.bdcredito in (select bdcodtpla from vsuc_select_contas tsel)) ';
  ELSE
     wsql = wsql||'where (tplac.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_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

  wsql = wsql||'and (tlan.bddata between '''||prdata_inicial||''' and '''||prdata_final||''') ';
  -- 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 ';
  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 tpla on (tpla.bdcodplapadrao = tx.bdcodplapadrao and tpla.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) ';

  wsql = wsql||'inner join vw_empresas_ref_atual emp on (emp.bdcodemp = tx.bdcodemp) ';

  --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
--     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 || ') ';
  end
  --alt:9167 - Fim

  wsql = wsql||'order by bdcodemp, bddata, bdconta, tx.bdcodter ';

  FOR EXECUTE STATEMENT wsql
  INTO :prchave, :prdata,
       :prempresa, :prnomeempresa, :prcnpjemp,
       :prcodplapadrao,
       :prlote, :prcompl, :prdcto,
       :wfilial, :prtipolancfilial,
       :prtipolan, :prchaveonline,
       :prcodhist, :prcodtphi, :prhistorico,
       :prconta, :prcodterceiroconta, :prconciliado, :prclass_conta, :prnome_conta, :prgrpcta, :wtipctaconta, :prparticipanteconta,
       :prcontra, :prcodterceirocontra, :prclass_contra, :prnome_conta_contra, :prparticipantecontra,
       :prdebito, :prcredito, :wdebcre,
       :prcodcentro, :prcc, :prtransacao, :prtranfechada, :wnometer DO
  BEGIN
    --alt:12505 - 07/10/2015 - Alterada regra do campo prempresa e prempresafilial, para detalhar corretamente matriz e filial de acordo com a opção "Lançar a". Pedro
    /*prcodempfilial = prempresa;
    wpos = POSITION(',', :prcodemp);
    IF (wpos <> 0) THEN
       BEGIN
         prcodempfilial = prempresa;
         IF (prcodmatriz IS NULL) THEN
            prcodmatriz = prempresa;
         prempresa = prcodmatriz;
       END*/

    if ((prtipolancfilial = 1) and (prdebito <> 0)) then
      prcodempfilial = wfilial;
    else if ((prtipolancfilial = 2) and (prcredito <> 0)) then
      prcodempfilial = wfilial;
    else
      prcodempfilial = prempresa;

    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;

    IF (prlcc = '') THEN
       prcc = 0;
    IF ((prdetalharctaparticipante = 1) AND (prparticipanteconta = 1) AND (wtipctaconta = 1)) 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(prcodterceiroconta, 8, '0');
       
         IF (prconcatenacodparticipante = 1) THEN
           BEGIN
             wpos = CHARACTER_LENGTH(:prcodterceiroconta);
             wpos = ((100 - wpos) - 3);
             wnometer = prcodterceiroconta||' - '||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 = wdebcre + 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
        --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
    IF (wpermite = 1) 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 VARCHAR(1024),
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,
PRIGNORAZERAMENTO INTEGER = 0,
PRIGNORASALDOANTERIOR 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),
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,
BDTIPOLANCFILIAL INTEGER,
BDVLRCONCILIADO NUMERIC(15,2),
BDVLRACONCILIAR NUMERIC(15,2),
BDCHAVEONLINE VARCHAR(120),
BDTRANSACAO INTEGER,
BDTRANFECHADA DM_BOOLEAN,
BDTIPOLAN INTEGER,
BDSEQCTA VARCHAR(7))
 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;
BEGIN
  -- BDCONCILIADOS = 0 TODOS 1 CONCILIADOS 2 NAO CONCILIADOS

  wconta     = 0;
  wsaldo     = 0;
  wordem     = 0;
  bdvlraconciliar = 0;
  bdvlrconciliado = 0;

  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.PRCHAVEONLINE, trazao.PRCODCENTRO, ';
  wsql = wsql||'TRAZAO.prtransacao, TRAZAO.prtranfechada, TRAZAO.prtipolan, trazao.prtipolancfilial ';

  wsql = wsql||'from vsuc_sp_retorna_razao_contas_x('''||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)||''',';
  --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))';

  -- 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.PRCHAVEONLINE, trazao.PRCODCENTRO, ';
       wsql = wsql||'TRAZAO.prtransacao, TRAZAO.prtranfechada, TRAZAO.prtipolan, trazao.prtipolancfilial ';
     
       wsql = wsql||'from vsuc_sp_retorna_razao_contas_x('''||TRIM(prcodemp)||''','''||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)) 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, ';
       wsql = wsql||'TRazao.prclass_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.PRTRANSACAO, trazao.PRTRANFECHADA, 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, /*: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, :bdchaveonline, :bdcodcentro,
           :bdtransacao, :bdtranfechada, :bdtipolan, :bdtipolancfilial 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: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 ((bdcod_terceiro_conta <> wcodter) AND (prdetalharctaparticipante = 1) AND (wparticipante = 1))) THEN
           BEGIN
             bdvlraconciliar = 0;
             bdvlrconciliado = 0;

             --alt:10644 - 24/03/2015 - Adicionado parâmetro para ignorar o saldo anterior. Pedro
             wsaldo = 0;
             if (PRIGNORASALDOANTERIOR = 0) 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
    --             wcodempefilial = bdempresa;
                 BEGIN
                   wsaldo = 0;
                   -- Detalhado por participante
                   IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdcod_terceiro_conta IS NOT NULL)) THEN
                      SELECT FIRST 1 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
                      --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;
    */
                   bdsaldoanterior = bdsaldoanterior + COALESCE(wsaldo,0);
                   wsaldo = bdsaldoanterior;
                 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;

        --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;
        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 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_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_COPIA_ATIVIDADES_MUNICIPAIS */
ALTER PROCEDURE SP_COPIA_ATIVIDADES_MUNICIPAIS(CODCIDNOVA INTEGER,
CODCIDCOPIAR INTEGER = 4445)
 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||')';
  EXECUTE STATEMENT wSQL;
END
^

/* Restore proc. body: SP_TIPODESCIDIOMAS */
ALTER PROCEDURE SP_TIPODESCIDIOMAS RETURNS(BDCODTIPODESCIDIOMA INTEGER,
BDCLASSIFICACAO VARCHAR(100),
BDCONFIGURA DM_BOOLEAN,
BDPERMITEABREVIADO DM_BOOLEAN,
BDPLANO INTEGER,
BDNIVEL INTEGER,
BDNIVEL1 VARCHAR(100),
BDNIVEL2 VARCHAR(100),
BDNIVEL3 VARCHAR(100),
BDCONSTANTE VARCHAR(30),
BDDESCRICAO VARCHAR(100))
 AS
begin
    for select tipos.BDCODTIPODESCIDIOMA, tipos.BDCLASSIFICACAO, tipos.BDCONFIGURA, tipos.BDPERMITEABREVIADO, tipos.BDCONSTANTE,
               char_length(tipos.BDCLASSIFICACAO) - char_length(replace(tipos.BDCLASSIFICACAO, '.', '')),
               case when planoCTA.BDCODPLAPADRAO is not null then planoCTA.BDCODPLAPADRAO
                    when planoCC.BDCODCENTRO is not null then planoCC.BDCODCENTRO
                    when planoFOR.BDCODPFOR is not null then planoFOR.BDCODPFOR end as BDCODPLANO,
               case when planoCTA.BDCODPLAPADRAO is not null then planoCTA.BDCODPLAPADRAO||' - '||planoCTA.BDNOME
                    when planoCC.BDCODCENTRO is not null then planoCC.BDCODCENTRO||' - '||planoCC.BDNOME
                    when planoFOR.BDCODPFOR is not null then planoFOR.BDCODPFOR||' - '||planoFOR.BDNOMPFOR
                    else tipos.BDDESCRICAO end as BDDESCRICAO
        from TTIPODESCIDIOMAS tipos
        left join TPLANO_PADRAO planoCTA on (tipos.BDCLASSIFICACAO = '03.00001.000001')
        left join TCENTROS planoCC on (tipos.BDCLASSIFICACAO = '03.00002.000001')
        left join VSUC_BASE_TFORMULA planoFOR on (tipos.BDCLASSIFICACAO = '03.00003.000001')
        order by tipos.BDCLASSIFICACAO, planoCTA.BDCODPLAPADRAO, planoCC.BDCODCENTRO, planoFOR.BDCODPFOR
    into :BDCODTIPODESCIDIOMA, :BDCLASSIFICACAO, :BDCONFIGURA, :BDPERMITEABREVIADO, :BDCONSTANTE, :BDNIVEL, :BDPLANO, :BDDESCRICAO do
    begin
      if ((BDNIVEL = 0) and ((BDCONFIGURA = 'FALSE') or (BDPLANO is not null))) then
        BDNIVEL1 = BDDESCRICAO;
      else if ((BDNIVEL = 1) and ((BDCONFIGURA = 'FALSE') or (BDPLANO is not null))) then
        BDNIVEL2 = BDDESCRICAO;
      else if ((BDNIVEL = 2) and ((BDCONFIGURA = 'FALSE') or (BDPLANO is not null))) then
        BDNIVEL3 = BDDESCRICAO;

      if (BDNIVEL < 2) then
        BDNIVEL3 = null;
    
      if (BDNIVEL < 1) then
        BDNIVEL2 = null;

      suspend;
    end
end
^

/* Restore proc. body: SP_VRHF_PBM_NO_ANO */
ALTER PROCEDURE SP_VRHF_PBM_NO_ANO(PREMP VARCHAR(32700),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WSQL2 varchar(1000);
declare variable WCODEMP integer;
declare variable WREFINI integer;
declare variable WREFFIM integer;
declare variable WCODBLOCOP integer;
declare variable WANO integer;
declare variable WMES varchar(2);
begin
  wsql = 'select EMP.bdcodemp from TEMPRESAS EMP ';

  if (premp is not null and premp <> '') then
    wsql = wsql||' where '||premp;

  for execute statement wsql into :wcodemp do
    begin
      bdcodemp = wcodemp;
      wrefini = CAST((:prano||'01') as INTEGER);
      wreffim = CAST((:prano||'12') as INTEGER);

      while (wreffim >= wrefini) do
        begin
          wsql2 = 'select first 1 BDCODCONFBLOCOP from VEF_BASE_TEMPPARGER where BDCODEMP = '||wcodemp||' and BDREFEMP <= '||wreffim||' order by BDREFEMP DESC ';
          wcodblocop = null;
          execute statement wsql2 into :wcodblocop;
          if (wcodblocop is not null and wcodblocop <> 0) then
            begin
              suspend;
              break;
            end

          if (CAST((SUBSTRING(wreffim FROM 5 FOR 2)) AS INTEGER) = 1) then
            begin
              wano = CAST((SUBSTRING(wreffim FROM 1 FOR 4)) AS INTEGER) - 1;
              wmes = '12';
              wreffim = CAST((CAST(wano AS VARCHAR(4))||wmes) AS INTEGER);
            end
          else
            begin
              wano = CAST((SUBSTRING(wreffim FROM 1 FOR 4)) AS INTEGER);
              wmes = SUBSTRING(wreffim FROM 5 FOR 2);
              wmes = CAST((CAST(wmes AS INTEGER) - 1) AS VARCHAR(2));
              while (strlen(wmes) < 2) do
                wmes = '0'||wmes;

              wreffim = CAST((CAST(wano AS VARCHAR(4))||wmes) AS INTEGER);
            end
        end
    end
end
^

/* Restore proc. body: VEF_COPIA_PLANO */
ALTER PROCEDURE VEF_COPIA_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
IMPOSTO VARCHAR(10))
 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);
BEGIN
  /* Zera os nomes das tabelas */
  wTabConf    = '';
  wTabQuadros = '';
  wTabFormula = '';
  /* Obtém os nomes das tabelas do plano */
  IF (IMPOSTO = 'DASN') THEN
    BEGIN
      wTabConf    = 'VEF_BASE_TCONFDASN';
      wTabQuadros = 'VEF_BASE_TCONFDASNQ';
      wTabFormula = 'VEF_BASE_TCONFDASNFORM';
    END

  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'||IMPOSTO||') FROM '||wTabConf;
          EXECUTE STATEMENT wSQL INTO codigonovo;
        END
      /* Limpa a tabela de formulas no código novo */
      wSQL = 'DELETE FROM '||wTabFormula||' WHERE BDCODCONF'||IMPOSTO||' = '||: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 = '';--'BDCODCONF'||IMPOSTO;
      FOR EXECUTE STATEMENT wSQL
        INTO wCampo DO
        BEGIN
          IF (wCampo <> 'BDCODCONF'||IMPOSTO) THEN
            wCamposInsert = wCamposInsert||','||TRIM(wCampo);
        END
      /* Cria insert da tabela de formulas */
      wSQL = 'INSERT INTO '||wTabFormula||' ('||'BDCODCONF'||IMPOSTO||wCamposInsert||') '||
             ' SELECT '||CodigoNovo||wCamposInsert||' FROM '||wTabFormula||' WHERE '||'BDCODCONF'||IMPOSTO||' = '||CODIGOCOPIAR;
      EXECUTE STATEMENT wSQL;
    END
END
^

/* Restore proc. body: VSUC_SP_COPIA_CONFIG_IDIOMAS */
ALTER PROCEDURE VSUC_SP_COPIA_CONFIG_IDIOMAS(PRIDIOMA INTEGER,
PRCODPLANO_DE INTEGER,
PRCODPLANO_PARA INTEGER,
PRPLANO INTEGER,
PROPCAOTROCA INTEGER)
 AS
declare variable wSQL varchar(1000);
declare variable wCODIDIOMA integer;
declare variable wCODPLANO integer;
declare variable wCODITEM integer;
declare variable wNOMCTAIDIOMA varchar(100);
BEGIN
  if (:prOpcaoTroca = 1) then
    begin
      if (prPlano = 0) then
        DELETE FROM PLANOS_TPLA_IDIOMAS WHERE BDCODPLAPADRAO = :prCodPlano_PARA AND BDCODIDIOMA = :prIdioma;
      else if (prPlano = 1) then
        DELETE FROM PLANOS_TPCC_IDIOMAS WHERE BDCODCENTRO = :prCodPlano_PARA AND BDCODIDIOMA = :prIdioma;
      else if (prPlano = 2) then
        DELETE FROM PLANOS_TFOR_IDIOMAS WHERE BDCODPFOR = :prCodPlano_PARA AND BDCODIDIOMA = :prIdioma;
    end

  wSQL = 'select config.BDCODIDIOMA, config.BDNOMCTAIDIOMA, '||:prCodPlano_PARA;

  if (prPlano = 0) THEN
    begin
      wSQL = wSQL||' as BDCODPLAPADRAO, PARA.BDCODTPLA from PLANOS_TPLA_IDIOMAS config';
      wSQL = wSQL||' inner join PLANOS_TPLA DE on (DE.BDCODPLAPADRAO = config.BDCODPLAPADRAO and DE.BDCODTPLA = config.BDCODTPLA)';
      wSQL = wSQL||'  left join PLANOS_TPLA PARA on (PARA.BDCODPLAPADRAO = '||:prCodPlano_PARA||')';
      wSQL = wSQL||' where config.BDCODIDIOMA = '||:prIdioma;
      wSQL = wSQL||'   and config.BDCODPLAPADRAO = '||:prCodPlano_DE;
      wSQL = wSQL||'   and Upper(DE.BDNOMCTA) = Upper(PARA.BDNOMCTA)';
    end
  else if (prPlano = 1) then
    begin
      wSQL = wSQL||' as BDCODCENTRO, PARA.BDCODTPCC from PLANOS_TPCC_IDIOMAS config';
      wSQL = wSQL||' inner join CENTROS_TPCC DE on (DE.BDCODCENTRO = config.BDCODCENTRO and DE.BDCODTPCC = config.BDCODTPCC)';
      wSQL = wSQL||'  left join CENTROS_TPCC PARA on (PARA.BDCODCENTRO = '||:prCodPlano_PARA||')';
      wSQL = wSQL||' where config.BDCODIDIOMA = '||:prIdioma;
      wSQL = wSQL||'   and config.BDCODCENTRO = '||:prCodPlano_DE;
      wSQL = wSQL||'   and Upper(DE.BDNOMCTA) = Upper(PARA.BDNOMCTA)';
    end
  else if (prPlano = 2) then
    begin
      wSQL = wSQL||' as BDCODPFOR, PARA.BDCODFOR from PLANOS_TFOR_IDIOMAS config';
      wSQL = wSQL||' inner join VSUC_BASE_TFORMULA_TPFO DE on (DE.BDCODPFOR = config.BDCODPFOR and DE.BDCODFOR = config.BDCODFOR)';
      wSQL = wSQL||'  left join VSUC_BASE_TFORMULA_TPFO PARA on (PARA.BDCODPFOR = '||:prCodPlano_PARA||')';
      wSQL = wSQL||' where config.BDCODIDIOMA = '||:prIdioma;
      wSQL = wSQL||'   and config.BDCODPFOR = '||:prCodPlano_DE;
      wSQL = wSQL||'   and Upper(DE.BDNOMFOR) = Upper(PARA.BDNOMFOR)';
    end

  if (:prOpcaoTroca = 3) then
    begin
      if (prPlano = 0) then
        begin
          wSQL = wSQL||'   and not exists(select * from PLANOS_TPLA_IDIOMAS ';
          wSQL = wSQL||'                  where BDCODPLAPADRAO = PARA.BDCODPLAPADRAO';
          wSQL = wSQL||'                    and BDCODTPLA = PARA.BDCODTPLA';
          wSQL = wSQL||'                    and BDCODIDIOMA = '||:prIdioma||')';
        end
      else if (prPlano = 1) then
        begin
          wSQL = wSQL||'   and not exists(select * from PLANOS_TPCC_IDIOMAS ';
          wSQL = wSQL||'                  where BDCODCENTRO = PARA.BDCODCENTRO';
          wSQL = wSQL||'                    and BDCODTPCC = PARA.BDCODTPCC';
          wSQL = wSQL||'                    and BDCODIDIOMA = '||:prIdioma||')';
        end
      else if (prPlano = 2) then
        begin
          wSQL = wSQL||'   and not exists(select * from PLANOS_TFOR_IDIOMAS ';
          wSQL = wSQL||'                  where BDCODPFOR = PARA.BDCODPFOR';
          wSQL = wSQL||'                    and BDCODFOR = PARA.BDCODFOR';
          wSQL = wSQL||'                    and BDCODIDIOMA = '||:prIdioma||')';
        end
    end

  for execute statement wSQL into :wCodIdioma, :wNomCtaIdioma, :wCodPlano, :wCodItem do
  begin
    if (prPlano = 0) then
      update or insert into PLANOS_TPLA_IDIOMAS values (:wCodIdioma, :wCodPlano, :wCodItem, :wNomCtaIdioma) matching (BDCODIDIOMA, BDCODPLAPADRAO, BDCODTPLA);
    else if (prPlano = 1) then
      update or insert into PLANOS_TPCC_IDIOMAS values (:wCodIdioma, :wCodPlano, :wCodItem, :wNomCtaIdioma) matching (BDCODIDIOMA, BDCODCENTRO, BDCODTPCC);
    else if (prPlano = 2) then
      update or insert into PLANOS_TFOR_IDIOMAS values (:wCodIdioma, :wCodPlano, :wCodItem, :wNomCtaIdioma) matching (BDCODIDIOMA, BDCODPFOR, BDCODFOR);
  end
END
^

/* Restore proc. body: VSUC_SP_MOVIMENTO_MENSAL */
ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
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,  :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
^

/* Creating trigger... */
CREATE TRIGGER TIDIOMAS_BI0 FOR TIDIOMAS
ACTIVE BEFORE INSERT POSITION 0 
AS
declare variable wCodigo integer;
begin
  if ((new.BDCODIDIOMA is null) or (new.BDCODIDIOMA = 0)) then
    begin
      select coalesce(max(BDCODIDIOMA), 0) +1 from TIDIOMAS into :wCodigo;
      new.BDCODIDIOMA = :wCodigo;
    end
end
^

CREATE TRIGGER TINDVAL_BIU0 FOR TINDVAL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0 
AS
begin
  new.BDDATAIND = CAST(SUBSTRING(new.BDREFIND FROM 5 FOR 2) ||'/'|| REPLACE(CASE WHEN CHAR_LENGTH(new.BDREFIND) > 6 THEN OVERLAY(new.BDREFIND PLACING '' FROM 1 FOR 6) ELSE '01' END, '00', '01') ||'/'|| OVERLAY(new.BDREFIND PLACING '' FROM 5 FOR 4) AS DATE);
end
^


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

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
;


/* Altering existing trigger... */
SET TERM ^ ;

ALTER TRIGGER VRH_EMP_TRESCISAO_PREVIA_BI0
AS
BEGIN
  NEW.BDREFRESCISAOPREV = CAST((SUBSTRING(CAST(NEW.BDDATARESCISAOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATARESCISAOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  IF (NEW.BDDATAPAGRESCISAOPREV  IS NULL) THEN
     NEW.BDDATAPAGRESCISAOPREV = NEW.BDDATARESCISAOPREV;

  NEW.BDREFPAGRESCISAOPREV = CAST((SUBSTRING(CAST(NEW.BDDATAPAGRESCISAOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATAPAGRESCISAOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (NEW.bdprojecaoavisoprev IS NOT NULL) THEN
     NEW.BDREFPROJECAOAVISOPREV = CAST((SUBSTRING(CAST(NEW.BDPROJECAOAVISOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDPROJECAOAVISOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     NEW.BDREFPROJECAOAVISOPREV = null;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_TRESCISAO_PREVIA_BU0
AS
BEGIN
  NEW.BDREFRESCISAOPREV = CAST((SUBSTRING(CAST(NEW.BDDATARESCISAOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATARESCISAOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  NEW.BDREFPAGRESCISAOPREV = CAST((SUBSTRING(CAST(NEW.BDDATAPAGRESCISAOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATAPAGRESCISAOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (NEW.bdprojecaoavisoprev IS NOT NULL) THEN
     NEW.BDREFPROJECAOAVISOPREV = CAST((SUBSTRING(CAST(NEW.BDPROJECAOAVISOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDPROJECAOAVISOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     NEW.BDREFPROJECAOAVISOPREV = null;
END
^

/* Alter Procedure... */
/* Alter (VSUC_SP_MOVIMENTO_MENSAL) */
ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
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,  :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
^

SET TERM ; ^

