Skip to content

Instantly share code, notes, and snippets.

@hevertonfreitas
Created December 12, 2017 16:55
Show Gist options
  • Save hevertonfreitas/44079471668a40deadc90f05f6c9ebfc to your computer and use it in GitHub Desktop.
Save hevertonfreitas/44079471668a40deadc90f05f6c9ebfc to your computer and use it in GitHub Desktop.
Digito verificador do código do IBGE (6 digitos)
create or replace function ibge_dv(codigo char(6))
returns char(1) as $$
select ((10 - resto) * (resto != 0)::int)::char(1)
from (
select
(
a135 +
left(a2, 1)::int + right(a2, 1)::int +
left(a4, 1)::int + right(a4, 1)::int +
left(a6, 1)::int + right(a6, 1)::int
) % 10 as resto
from (
select
a[1] + a[3] + a[5] as a135,
to_char(a[2] * 2, 'FM09') as a2,
to_char(a[4] * 2, 'FM09') as a4,
to_char(a[6] * 2, 'FM09') as a6
from (
select string_to_array(codigo, null)::integer[] as a
) s
) s
) s
;
$$ language sql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment