Skip to content

Instantly share code, notes, and snippets.

@rafa-acioly
Created April 25, 2018 00:38
Show Gist options
  • Save rafa-acioly/73d2921b772949f44c9c2299a178081c to your computer and use it in GitHub Desktop.
Save rafa-acioly/73d2921b772949f44c9c2299a178081c to your computer and use it in GitHub Desktop.
functions in sql and plpgsql
create or replace function tipo(varchar)
returns setof notas as
'
SELECT n.* FROM notas n, tiponota t
where t.nome = $1
and t.codigo = n.tipo_nota;
'
language 'sql';
-- select tipo('p1');
create or replace function notaexiste(varchar)
returns integer as
$$
declare existe integer;
begin
existe := (select count(*) from notas nt, tiponota tpn
where tpn.nome = $1
and tpn.codigo = nt.tipo_nota);
if existe >= 1 then
raise notice 'Nota existe!!';
return existe;
end if;
raise notice 'Nota não existe!';
return 0;
end;
$$
language 'plpgsql';
-- select notaexiste('p1x');
create or replace function inserirnota(rgm numeric, codigo numeric, tipo varchar, nota numeric)
returns void as
$$
declare existe integer = (select notaexiste(tipo));
begin
if existe >= 1 then
declare idTipo numeric = (select codigo from tiponota where nome = tipo);
insert into notas values(rgm, codigo, idTipo, nota);
raise notice 'Inserido com sucesso!';
return;
end if;
raise notice 'Não foi possivel inserir!';
return;
end;
$$
language 'plpgsql';
-- select inserirnota(123, 951, 'p1', 10);
create or replace function consultaraluno(numeric, varchar, varchar)
returns setof notas as
'
select n.* from notas n, tiponota t where
t.codigo = $3 and n.tipo_nota = t.codigo
and n.rgm_aluno = $1 and n.codigo_disciplina = $2;
'
language 'sql';
-- consultaraluno(123, 951);
create or replace function media(rgm numeric, disci varchar)
returns numeric as
$$
begin
declare p1 numeric = (select sum(notas.nota) from notas where rgm_aluno = rgm);
declare p2 numeric = (select sum(notas.nota) from notas where rgm_aluno = rgm);
declare media numeric = (p1+p2)/2;
return media;
end;
$$
language 'plpgsql';
-- select media(123, 122);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment