Skip to content

Instantly share code, notes, and snippets.

@dxdns
Last active March 25, 2024 17:25
Show Gist options
  • Save dxdns/f439cf17fdfcaa7f1a5bdda45c4f1ee0 to your computer and use it in GitHub Desktop.
Save dxdns/f439cf17fdfcaa7f1a5bdda45c4f1ee0 to your computer and use it in GitHub Desktop.
comandos sql | firebirdsql
reabrir uma conta a receber, que está como quitada, mas não tem o recibo de baixa
update contas_receber set vlr_quitacao = 0, situacao = 'ABERTO'
where id not in (select id_conta from recibo_receber_itens where id_conta = contas_receber.id) and situacao = 'QUITADO'
PARA AJUSTAR ESTOQUE NOTA DE COMPRA NO X COLOCAR O NUMERO DA NOTA DE COMPRA
Somar ou subtrair. Basta mudar na ultima linha o sinal de + para somar e - para diminuir
merge into produtos a
using(select d.id_produto, sum(d.quantidade) as quantidade from nota_compra_detalhe d
left join nota_compra c on c.id = d.id_nfe where c.nota = X
group by d.id_produto) b
on (a.id_produto = b.id_produto)
when matched then update set
a.estoque = a.estoque + b.quantidade
AJUSTAR TRIBUTAÇÃO DO PRODUTO PELA NOTA DE COMPRA
merge into produtos a
using(select d.id_produto, substring(d.cst from 1 for 1) as origem,
case when substring(d.cst from 2 for 2) = 20 then 
substring(d.cst from 1 for 1)||'00' 
else 
substring(d.cst from 1 for 1)||substring(d.cst from 2 for 2) end as cst
from NOTA_COMPRA_DETALHE d
where d.id = (select max(e.id) from nota_compra_detalhe e
where e.id_produto = d.id_produto group by e.id_produto)) b
on (a.id_produto = b.id_produto)
when matched then update set
a.origem = b.origem, a.cst = b.cst
update PRODUTOS 
set ST = 'F', CSOSN = 500, CST = '060', ECF_ICMS_ST = 'FF', ICMS = 0
where substring(CST from 2 for 2) = '60';

update PRODUTOS 
set ST = 'T', CSOSN = 102, CST = '000', ECF_ICMS_ST = '18', ICMS = 18 
where substring(CST from 2 for 2) = '00'; 

update PRODUTOS 
set ST = 'I', CSOSN = 103, CST = '040', ECF_ICMS_ST = 'II', ICMS = 0
where substring(CST from 2 for 2) = '40';
ALTERAR CHAVE NFE POR NUMERAÇÃO
update NFE set NFE_CHAVE_ORIGINAL = 'xxx', NFE_CHAVE_ACESSO = 'xxx'
where  NFE_NUMERO = xxx
alterar csosn para 102 onde for 101
update PRODUTOS set CSOSN = 102 WHERE CSOSN = 101
ALTERAR NCM DOS PRODUTOS
update PRODUTOS set NCM = '87141000'
where NCM = 'xxxxxx'
ALTERAR NUMERO NFCE
update NFCE set NFCE_NUMERO = y
where NFCE_NUMERO = x
ALTERAR NUMERO NFE
update NFE set NFE_NUMERO = y
where NFE_NUMERO = x
ALTERAR SERIE NFCE
update nfce set NFCE_SERIE = y
where nfce_numero = x
NFCE EM CONTIGENCIA
update NFCE set NFCE_STATUS = 'CONTIGENCIA'
where  NFCE_NUMERO = x
alterar tipo de item
update produtos set tipo_item = 1
exemplo de tipos
  • mercadoria para revenda = 0
  • materia prima = 1
ALTERAR TIPO DE OPERAÇÃO NFE

(pode ser utilizado como 'Interna' OU 'Interestadual')

update nfe set tipo_operacao = 'Interna'
where nfe_numero = x
ALTERAR TIPO DE PAGAMENTO - CONTAS A PAGAR DE PZ PARA DP
update contas_pagar set tipo_doc = 'DP'
where tipo_doc = 'PZ'
ALTERAR UNIDADE DE MEDIDA DOS PRODUTOS DE PARES PARA PR
(exemplo: pode ser utilizado de 'UNID' para 'UN')
update produtos set unidade_comecial = 'PR' where unidade_comecial = 'PARES'
update produtos set unidade_comecial = 'UN' where char_length(unidade_comecial) > 3
o valor informado nao pode ser maior que o valor restante
update contas_pagar set vlr_conta = trunc(vlr_conta,2)
ALTERAR CHAVE NFCE
update nfce set nfce_chave_acesso = 'XXXXXXXXXXX', nfce_chave_acesso_original = 'XXXXXXXXXXX'
where nfce_numero = y
REMOVER VINCULO DO CLIENTE EM VENDAS NO NFCE

(utilizado quando apresenta erros em relatórios após excluir clientes)

update nfce set id_cliente = null
where id_cliente not in (select clientes.id_cliente from clientes)
UTILIZADO PARA INSERIR O CLIENTE EM UMA TRANSFERENCIA
INSERT INTO EXPORTACAO (CNPJ) VALUES ('14619790000100');
adicionar zero no final do barras para produtos de balança
update produtos
set barras = RPAD(BARRAS,7,0)
where
UNIDADE_COMECIAL = 'KG'
COMPARAR NFCE ITENS
with recursive itens as (
select id_nfce, sum(total_item) as total from nfce_itens where id_nfce in (
SELECT id FROM nfce where data_venda between '2020/09/01' and '2020/09/30' and nfce_status = 'AUTORIZADO'
) and cancelado = 'N' --and valor_total <> total_item
group by id_nfce
)
select a.*, itens.*, total - valor_final as diferenca
from (SELECT id, valor_final FROM nfce where data_venda between '2020/09/01' and '2020/09/30' and nfce_status = 'AUTORIZADO') a
left join itens on itens.id_nfce = a.id
where valor_final <> total
CONSULTAR PULO DE NUMERAÇÃO
execute block
returns (teste int)
as
declare variable iID int;
declare variable idNUM int;
begin

  iID = 0;

  for select distinct id_cliente from clientes where id_cliente is not null order by id_cliente into :idNUM do
  begin
    iID = iID + 1;

    while (iID < idNUM) do begin
      TESTE = iID;
      iID = iID + 1;
      suspend;
    end

  end


end
Corrige a UN dos PRODUTOS do inventário
update inventario_itens set unidade = 'UN' 
where unidade not in 
(select sigla from unidade_medida where sigla = unidade)
Corrige a UN dos PRODUTOS
update produtos set unidade_comecial = 'UN' 
where unidade_comecial not in 
(select sigla from unidade_medida where sigla = unidade_comecial)
CORRIGIR BASE ICMS NFCE
merge into nfce a
using(select i.id_nfce, sum(i.total_item) as bc_icms, 
sum((i.total_item * i.TAXA_ICMS) / 100) as icms from nfce_itens i 
where i.TAXA_ICMS > 0 and i.CANCELADO = 'N' group by i.id_nfce) b
on (a.id = b.id_nfce)
when matched then update set
a.base_icms = b.bc_icms, a.icms = b.icms
ALTERAR A MARGEM DE VENDA COM BASE NO CUSTO DO PRODUTO
update produtos set custo=custo *1.3
update produtos set margem_atac = x
update produtos set valor_atacado = x
update produtos set valor_atacado = custo*margem_atac
update produtos set valor_atacado = valor_venda*margem_atac
update produtos set margem = 40
update produtos set  valor_venda = valor_venda *1.4
DELETAR INVENTÁRIO MENSAL PELA DATA DO MOVIMENTO
delete from inventario_mensal
where dt_movimento = '2019-12-31'
DELETAR NFCE POR NUMERAÇÃO
delete FROM NFCE where NFCE_NUMERO = x
DELETAR TODOS OS PRODUTOS INATIVOS
delete from produtos
where status = 'INATIVO'
Deletar todos os clientes
delete from clientes
Para deletar todas as vendas no dav
delete from dav
remove mde duplicado
delete from mde
where 
  chave in 
  (select chave
  from mde
  group by chave
  having count(chave) > 1)
Deletar todas as nfce
delete from nfce
Deletar todas NFE
delete from nfe
Para deletar todas as notas de compra
delete from nota_compra
utilizado quando nao consegue editar ou excluir uma conta a pagar por causa do desconto
no lugar do x informar o id da conta
update contas_pagar set vlr_desconto = 0
where id = x
Descrição do produto + referência
update produtos set produto = produto || ' ' ||referencia
resolve o erro de cst ao gerar o inventário
alter table inventario_itens
add CST            VARCHAR(3),
add BC_ICMS        NUMERIC(18,2),
add VLR_ICMS       NUMERIC(18,2)
Estoque é igual a zero onde o estoque for nulo
update produtos set estoque = 0
where estoque is null
FECHAR CUPOM EM ABERTO NO NFCE
update NFCE set STATUS_VENDA = 'F' where STATUS_VENDA = 'A'
FILTRAR CLIENTES POR CIDADE (NFCE)
select * from nfce 
left join CLIENTES on CLIENTES.ID_CLIENTE = nfce.ID_CLIENTE
where CLIENTES.CODIGO_MUNICIPIO = 2917003 and nfce.DATA_VENDA = '2019-03-14'
GERAR CÓDIGO DE BALANÇA
update produtos
set barras = '2' || lpad(id_produto, 4, '0')||''
where unidade_comecial = 'KG'
ICMS SPED
update PRODUTOS set ecf_icms_st = substring(icms from 1 for 2) where ST = 'T' and ecf_icms_st is null
update nfce_itens set icms = (base_icms * taxa_icms) / 100 where taxa_icms > 0 and cancelado = 'N'
update nfce set icms = (select sum(icms) from NFCE_ITENS i where i.cancelado = 'N' and i.id_nfce = nfce.id)
where id = (select id_nfce from NFCE_ITENS i where i.cancelado = 'N' and i.id_nfce = nfce.id group by id_nfce)
ICMS ST F1 ITENS
update NFCE_ITENS set ICMS_ST = 'F1'
where cst = 060
INATIVAR TODOS OS PRODUTOS COM ESTOQUE ZERO
update produtos set status = 'INATIVO'
where estoque = 0
INSERIR CLIENTE NFCE
update nfce set id_cliente = x
where nfce_numero = y
INSERIR CLIENTE NA NFE
(geralmente utilizado quando ocorre duplicidade, pois já existe outra nota na sefaz com um destinatário diferente)
update nfe set id_cliente = x
where nfe_numero = y
INSERIR FORMA DE PAGAMENTO ONDE NÃO TEM PARA TODAS AS VENDAS DO DAV
(forma de pagamento inserida 'OUTROS')
insert into DAV_TOTAL_TIPO_PGTO (ID_VENDA_CABECALHO, ID_TIPO_PAGAMENTO, VALOR, estorno)
select dav.id as id_venda_cabecalho, '12' as ID_TIPO_PAGAMENTO, dav.total_documento as
valor, 'N' as estorno from dav
left join DAV_TOTAL_TIPO_PGTO on DAV_TOTAL_TIPO_PGTO.ID_VENDA_CABECALHO = DAV.ID
where DAV_TOTAL_TIPO_PGTO.id is null
INSERIR FORMA DE PAGAMENTO ONDE NÃO TEM PARA TODAS AS VENDAS DO NFCE
(forma de pagamento inserida 'OUTROS')
insert into NFCE_TOTAL_TIPO_PGTO (ID_VENDA_CABECALHO, ID_TIPO_PAGAMENTO, VALOR, estorno)
select nfce.id as id_venda_cabecalho, '12' as ID_TIPO_PAGAMENTO, nfce.total_documento as
valor, 'N' as estorno from NFCE 
left join NFCE_TOTAL_TIPO_PGTO on NFCE_TOTAL_TIPO_PGTO.ID_VENDA_CABECALHO = NFCE.ID
where NFCE_TOTAL_TIPO_PGTO.id is null
INUTILIZAR NFCE POR NUMERAÇÃO
update nfce set nfce_status = 'INUTILIZADO'
where nfce_numero = x
INUTILIZAR NFCE POR NUMERAÇÃO E SÉRIE
update nfce set nfce_status = 'INUTILIZADO'
where nfce_numero = x and nfce_serie = y
INUTILIZAR NFCE POR STATUS
update nfce set nfce_status = 'INUTILIZADO'
where nfce_status = 'PROCESSADO'
FILTRAR NFCE POR NUMERO ONDE O STATUS É IGUAL A PROCESSADO
select n.nfce_numero, i.item, i.QUANTIDADE, i.VALOR_UNITARIO, i.VALOR_TOTAL 
from nfce_itens i
left join nfce n on n.id = i.id_nfce
where n.NFCE_STATUS = 'PROCESSADO' and n.nfce_numero = X
order by n.nfce_numero
LIMPAR O CÓDIGO DE BARRAS DE TODOS OS PRODUTOS
update produtos set barras = null
LIMPAR O CAMPO NCM DE TODOS OS PRODUTOS
update PRODUTOS set NCM = ''
LIMPAR CAMPO REFERENCIA DE TODOS OS PRODUTOS
update produtos set referencia = null
inserir nome da marca no campo referencia, para pesquisar a referencia pelo nome da marca
SET referencia = (
    SELECT PRODUTOS_MARCA.marca
    FROM PRODUTOS_MARCA
    WHERE PRODUTOS_MARCA.id = produtos.marca
)```
MARCAR TODOS OS PRODUTOS KG COMO CHECKOUT
update produtos set pesado_checkout = 'S'
where unidade_comecial = 'KG'
ALTERAR CNPJ DO MDE IGUAL AO CNPJ DO CERTIFICADO
update mde set cnpj = cnpj_certificado
where numero = x
ALTERAR CHAVE MDFE
update MDFE set mdfe_chave_acesso = 'XXX', mdfe_chave_original = 'XXX'
where mdfe_numero = Y
FAÇA AS ALTERAÇÕES NO COMANDO
  • Y = Número do mdfe
  • XXX = Chave de acesso do mdfe
  • XXX > mdfe_chave_acesso = mdfe_chave_original
ALTERAR TOTAL DO ITEM COM BASE EM QUANTIDADE E VALOR
update nfce_itens set total_item = valor_unitario * quantidade
where id_nfce = x
CORRIGIR VALOR TOTAL DO NFCE COM BASE NA FORMA DE PAGAMENTO
update nfce n 
set n.valor_final = (select sum(p.valor) from NFCE_TOTAL_TIPO_PGTO p where p.id_venda_cabecalho = n.id)
where n.id in (select p.id_venda_cabecalho from NFCE_TOTAL_TIPO_PGTO p where p.id_venda_cabecalho = n.id) 
ALTERAR SITUAÇÃO TRIBUTÁRIA DE UM ITEM (NFE)
update nfe_itens set icms_sit_tributaria = 101
where id_nfe = x
Reordenar ID estoque
(executar update separadamente, pois são três comandos)
update produtos set id_produto = id_produto - 9999999;
update produtos set id_produto = 0 where id_produto = x;
update produtos set id_produto = 1 + (select max(i.id_produto) from produtos i);
PERMITIR TROCO EM UMA DETERMINADA FORMA DE PAGAMENTO
update dav_formas_pagamento set permite_troco = 'S'
where id = 9
ZERAR PIS E COFINS DE SAIDA EM TODOS OS PRODUTOS MONOFASICOS
update produtos set ALIQ_PIS_SAIDA = 0
where CST_PISCOFINS_SAIDA = 4
update produtos set ALIQ_COFINS_SAIDA = 0
where CST_PISCOFINS_SAIDA = 4
ALTERAR PIS E COFINS DE SAIDA (LUCRO REAL)
update produtos set ALIQ_PIS_SAIDA = 1.65, ALIQ_COFINS_SAIDA = 7.60
where CST_PISCOFINS_SAIDA = 1
trocar ncm pelo inicio da descrição do produto
update produtos set ncm = 'xxxxx' where produto LIKE 'DESCRIÇÃO%'
redução da base de icms no cadastro dos produtos por grupo
update produtos set RED_BASE_ICMS = x
where GRUPO = y
Corrigir diferença do relatorio de vendas por periodo > cfop
update nfce_itens set total_item = valor_total
where total_item <> valor_total and cancelado = 'N'
REMOVER O CLIENTE DE TODAS AS VENDAS NO DAV
(geralmente utilizado para resolver erro de violação ao tentar gerar um relatório, pois existe vendas vinculadas
a um cliente especifico e o cliente foi excluído)
update dav set ID_CLIENTE = null
where ID_cliente = x
(em id_cliente deve ser informado o numero do cliente)
REMOVER O CLIENTE DE TODAS AS VENDAS NO NFCE
(geralmente utilizado para resolver erro de violação ao tentar gerar um relatório, pois existe vendas vinculadas
a um cliente especifico e o cliente foi excluído)
update NFCE set ID_CLIENTE = null
where ID_CLIENTE = x
(em id_cliente deve ser informado o numero do cliente)
REMOVER DESCONTO DE UM CONTAS A PAGAR ESPECIFICO
update contas_pagar set vlr_desconto = 0
where id = 308
REMOVER ESPAÇO ANTES DA DESCRIÇÃO DO PRODUTO
update produtos set produto = trim(produto)
REVERTER CANCELAMENTO DE NFCE
(geralmente utilizado para reverter um cancelamento de uma nfce que está como autorizada, mas o cupom e itens está como cancelado
gerando divergência no relatório de mapa resumo)
update nfce_total_tipo_pgto p set p.estorno = 'N' where p.id_venda_cabecalho in (
select n.id from NFCE n
where n.nfce_status = 'AUTORIZADO' and n.CUPOM_CANCELADO = 'S' and p.id_venda_cabecalho = n.id  
)
update nfce_itens i set i.cancelado = 'N' where i.id_nfce in (
select n.id from NFCE n 
where n.nfce_status = 'AUTORIZADO' and n.CUPOM_CANCELADO = 'S' and i.id_nfce = n.id
)
update nfce set CUPOM_CANCELADO = 'N', STATUS_VENDA = 'F'
where nfce_status = 'AUTORIZADO'
REVERTER QUITACÃO NO CONTAS A PAGAR
update contas_pagar set situacao = 'ABERTO', DT_QUITACAO = null, VLR_QUITACAO = null
where id = 1
compara bc_icms dos itens com bc_icms da venda e retorna os registros que contem diferença
pela numeração
SELECT i.*, n.base_icms as bc_venda
FROM (
  SELECT I.id_nfce, SUM(I.base_icms) AS BC_ITENS
  FROM NFCE N
  INNER JOIN NFCE_ITENS I ON I.id_nfce = N.ID
  WHERE NFCE_NUMERO BETWEEN 416525 AND 417270 AND CUPOM_CANCELADO = 'N' AND
    N.nfce_status IN ('AUTORIZADO', 'CONTIGENCIA') AND I.cancelado = 'N'
  GROUP BY 1 ) i
inner join nfce n on n.id = i.id_nfce
where i.bc_itens <> n.base_icms
pela data
SELECT i.*, n.base_icms as bc_venda
FROM (
  SELECT I.id_nfce, SUM(I.base_icms) AS BC_ITENS
  FROM NFCE N
  INNER JOIN NFCE_ITENS I ON I.id_nfce = N.ID
  WHERE data_venda BETWEEN '2020-10-09' AND '2020-10-09' AND CUPOM_CANCELADO = 'N' AND
    N.nfce_status IN ('AUTORIZADO', 'CONTIGENCIA') AND I.cancelado = 'N'
  GROUP BY 1 ) i
inner join nfce n on n.id = i.id_nfce
where i.bc_itens <> n.base_icms
SOMAR VALOR DE UMA COLUNA
SELECT SUM(nome_coluna)
FROM nome_tabela
WHERE condicao
inserir dados do cartão no sped, serve pra gerar o (bloco 1601)
update nfce_total_tipo_pgto set cartao_dc = 'C' where id_tipo_pagamento = xx
ALTERAR DATA DE SAIDA/VENDA NO NFCE (IGUAL A DATA DE EMISSÃO)
update NFCE set nfce_data_saida = nfce_data_emissao
update NFCE set data_venda = nfce_data_emissao
Aplicar a substituição tributária nos produtos que tem CEST
update PRODUTOS
set ST = 'F', CSOSN = 500, CST = '060', ECF_ICMS_ST = 'FF', ICMS = 0
where char_length(CEST) > 0
TOTAL DO ITEM É IGUAL AO VALOR UNITÁRIO VEZES A QUANTIDADE (NFCE_ITENS)
update nfce_itens set total_item = valor_unitario * quantidade
where id_nfce = x
CORRIGIR TRIBUTAÇÃO DOS PRODUTOS
(geralmente utilizado após uma conversão de dados)
SUBSTITUIÇÃO TRIBUTARIA
update PRODUTOS
set ST = 'F', CSOSN = 500, CST = '060', ECF_ICMS_ST = 'FF', ICMS = 0
where ICMS = 0
TRIBUTADO (exemplo 18%)
update PRODUTOS 
set ST = 'T', CSOSN = 102, CST = '000', ECF_ICMS_ST = '18', ICMS = 18
where ICMS = 18
ISENTO
update PRODUTOS 
set ST = 'I', CSOSN = 103, CST = '040', ECF_ICMS_ST = 'II', ICMS = 0
where ICMS = 0
NÂO TRIBUTADO
update PRODUTOS 
set ST = 'N', CSOSN = 400, CST = '041', ECF_ICMS_ST = 'NN', ICMS = 0
where ICMS = 0
VALOR DE VENDA É IGUAL AO CUSTO
update produtos set valor_venda = custo
preço de venda pela margem
UPDATE PRODUTOS SET VALOR_VENDA = ( 0.24* CUSTO ) + CUSTO
COMANDO UTILIZADO PARA CORRIGIR (ERRO DE TAXA STRET NO NFCE)
ALTER TABLE NFCE ADD FCP_VALOR
NUMERIC ( 18, 2) DEFAULT 0, ADD FCP_VALORST
NUMERIC ( 18, 2) DEFAULT 0, ADD FCP_VALORRET
NUMERIC ( 18, 2) DEFAULT 0
ALTER TABLE NFCE_ITENS ADD FCP_TAXA_STRET NUMERIC( 18, 2)
ALTER TABLE NFCE_ITENS ADD ANP_GLP_PESO_LIQ NUMERIC( 18, 4)
ADICIONAR O ESTOQUE EM UMA NFE QUE NÃO VOLTOU O ESTOQUE APÓS O CANCELAMENTO
merge into PRODUTOS b
using NFE_ITENS p
on p.id_produto = b.id_produto and p.id_nfe = X
when matched then
update set b.estoque = b.estoque + p.quantidade
Onde tá o X por o ID da NFe
(digitar o ID da nota não o NUMERO da NFe)
ZERAR O ESTOQUE DE TODOS OS PRODUTOS NEGATIVOS
update PRODUTOS set ESTOQUE = 0
where estoque < 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment