Skip to content

Instantly share code, notes, and snippets.

@KentaYamada
Last active July 31, 2017 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KentaYamada/e907b14f20ed01fc4e46d8d0cdb5014e to your computer and use it in GitHub Desktop.
Save KentaYamada/e907b14f20ed01fc4e46d8d0cdb5014e to your computer and use it in GitHub Desktop.
PL/PgSQL example
-- clean up.
drop table if exists persons;
drop function if exists entry_person(text, integer);
-- initialize.
create table persons (
name text
,age integer
);
create or replace function entry_person(p_name, p_age integer)
returns boolean as
$$
declare
affected_row integer;
saved boolean;
begin
update persons set
name = p_name
,age = p_age
where name = p_name;
get dianostics affected_row = row_count;
if affected_row < 1 then
insert into persons (
name
,age
) values (
p_name
,p_age
);
end if;
get diagnostics affected_row = row_count;
if affected_row < 1 then
saved = FALSE;
else
saved = TRUE;
end if;
return saved;
end;
$$ language plpgsql;
-- testing.
select entry_person('Taro', 24);
select * from persons;
CREATE OR REPLACE FUNCTION find_persons()
RETURNS TABLE(name TEXT)
LANGUAGE 'plpgsql'
AS $$
BEGIN
RETURN QUERY
SELECT t.name FROM persons as t
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment