Skip to content

Instantly share code, notes, and snippets.

@neos1803
Created May 28, 2024 07:34
Show Gist options
  • Save neos1803/c413831a7bc9779f2c93d1601995ffba to your computer and use it in GitHub Desktop.
Save neos1803/c413831a7bc9779f2c93d1601995ffba to your computer and use it in GitHub Desktop.
How to create a postgresql function that increment a string lead with 0000
CREATE OR REPLACE FUNCTION public.after_update()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
declare
maximum character(5);
nextMax character(5);
BEGIN
-- Find max urutan
select max(tnp.urutan) into maximum from something;
-- Increment max
nextMax := lpad((cast(maximum as integer) + 1)::character(5), 5, '0');
-- Handle 99999 value
if (maximum = '99999')
then return null;
else
insert into something;
return null;
end if;
END;
$function$
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment