-
-
Save leoclaro/0e69a37dba1d8fb025bac91cac16cdea to your computer and use it in GitHub Desktop.
Digito verificador do código do IBGE (6 digitos)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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