Reputation: 1
I want to write a Postgres Function, which returns either a table or an error after i pass a value to it. For Example: Looking for the owner of a smartphone works.
create or replace function get_handy_besitzer (ide int)
returns table (
h_kostenstellename varchar,
h_edvkennung varchar,
h_bezeichnung varchar
)
language plpgsql
as $$
begin
return query
select
kostenstellename,
edvkennung,
bezeichnung
from
anlagen
where
id = ide;
end;$$
But when i put the excpetion at the end like
create or replace function get_handy_besitzer (ide int)
returns table (
h_kostenstellename varchar,
h_edvkennung varchar,
h_bezeichnung varchar
)
language plpgsql
as $$
begin
return query
select
kostenstellename,
edvkennung,
bezeichnung
from
anlagen
where
id = ide;
exception
when no_data_found then
raise exception 'id not found';
end;$$
it doesn't work. But why?
I tried using the record type as a return, but that resulted in another error. I really dont know what to do, i dont even find any example with a function that handles exceptions.
Edit: My goal is to specify the exception for certain sql states like
exception
when sqlstate 'P0002' then
raise exception 'id not found';
exception
when sqlstate '22P02' then
raise exception 'try it with a number';
Upvotes: 0
Views: 496
Reputation: 121604
Your function is intended to raise an exception, not to handle one.
return query
select
kostenstellename,
edvkennung,
bezeichnung
from
anlagen
where
id = ide;
if not found then
raise exception 'no data found';
end if;
Read about Reporting Errors and Messages and Obtaining the Result Status
Upvotes: 2