Skip to content

Instantly share code, notes, and snippets.

@leoclaro
Forked from hevertonfreitas/dv_ibge.sql
Created October 17, 2018 20:17
Show Gist options
  • Save leoclaro/0e69a37dba1d8fb025bac91cac16cdea to your computer and use it in GitHub Desktop.
Save leoclaro/0e69a37dba1d8fb025bac91cac16cdea 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