Avoid 'ambiguous column' in simple PostgreSQL function returning table - postgresql

Suppose I have the following table, function and execution:
create table mytable (a INTEGER, b INTEGER);
create function test(q INTEGER)
returns table(a INTEGER, b INTEGER)
as
$body$
begin
return query select a,b from mytable;
end;
$body$
language plpgsql STABLE;
select * from test(1);
I get an 'ambiguous column name' error. I can get rid of it by changing the selection to "select t.a, t.b from mytable t" (per some similar-ish posts). But it seems very odd to have to qualify the column names when there is only 1 table in my query. I'm porting code that has quite a lot of stored procedures selecting from single tables (in various ways) and returning a table with columns that have the same name. Is there a better way than this of avoiding the error, and still having an output table with the same column names?
Thanks for any leads.

you can (you should) to use aliases.
create table mytable (a INTEGER, b INTEGER);
create function test(q INTEGER)
returns table(a INTEGER, b INTEGER)
as
$body$
begin
return query select mt.a, mt.b from mytable mt;
end;
$body$
language plpgsql STABLE;
select * from test(1);

maybe thats an option, using format and query execute:
( as the error says, it doesnt know which a to take, the pl/pgSQL variable or a columname )
create function test(q INTEGER)
returns table(a INTEGER, b INTEGER)
as
$body$
declare
lsQueryExecute text;
begin
lsQueryExecute = format('select a,b from mytable');
return query execute lsQueryExecute;
end;
$body$
language plpgsql STABLE;

Related

parameter name used more than once in postgresql

My project used MS SQL, and postgresql so I can't change my parameter to another name, something like below
CREATE OR REPLACE FUNCTION myfunction( ReservationNo integer)
RETURNS TABLE("reservationno" integer) AS
$BODY$
begin
RETURN QUERY
select
rr.ReservationNo
FROM Mytable rr
WHERE rr.ReservationNo = myfunction.ReservationNo;
end
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
ALTER FUNCTION myfunction(integer)
OWNER TO postgres;
But it give me an error
parameter name "reservationno" used more than once
How can I fix it?
You can change it to a SQL function, which doesn't have this problem:
CREATE OR REPLACE FUNCTION myfunction( ReservationNo integer)
RETURNS TABLE("reservationno" integer) AS
$BODY$
select rr.ReservationNo
FROM Mytable rr
WHERE rr.ReservationNo = myfunction.ReservationNo;
$BODY$
LANGUAGE sql stable
;

How to get entire table data or multiple rows returned from a function in PG/PLSQL with pgAdmin 4.2.?

I tried using setof and table. While creating function in pgAdmin 4.2 there is no return type called setof or table. If I create function with setof and table name as a selected return type, it only returns one row of table.
CREATE FUNCTION pgsql_returnrecords() RETURNS SETOF RECORD(name char, city, char, id integer) AS
$BODY$
DECLARE
rec RECORD;
BEGIN
select name,city,id INTO rec from test;
return next rec;
END;
$BODY$ language plpgsql;
I want my function to return table data with all rows and columns.
It's either returns setof record or returns table(....) or setof table_name With returns setof record you have to specify the column names when using the function.
You are also not returning a complete result, because you only fetch a single row, put it into the record and return that. To return a real "set" you need to use return query in PL/pgSQL. But such a function is much better written as a SQL function:
CREATE FUNCTION pgsql_returnrecords()
RETURNS table(name text, city text, id integer)
AS
$BODY$
select name,city,id
from test;
$BODY$
language sql;
If you want to always return a complete row from the table test you can simplify that using returns setof test instead of returns table(..)
CREATE FUNCTION pgsql_returnrecords()
RETURNS setof test
AS
$BODY$
select *
from test;
$BODY$ language sql;
Or, if you insist on PL/pgSQL:
CREATE FUNCTION pgsql_returnrecords()
RETURNS table(name text, city text, id integer)
AS
$BODY$
BEGIN
return query
select name,city,id
from test;
END;
$BODY$
language plpgsql;
In both cases you have to use the function like a table in the FROM clause:
select *
from pgsql_returnrecords() ;

PostgreSQL ambiguous column reference after specifying column name

I have a function like this
CREATE OR REPLACE FUNCTION factors_apart_sa()
RETURNS TABLE(surf_area integer, sa_factor numeric) AS
$BODY$
BEGIN
RETURN QUERY SELECT factors_apart_sa.surf_area, factors_apart_sa.sa_factor FROM factors_apart_sa;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
After calling this function I get an error:
column reference "factors_apart_sa.surf_area" is ambiguous
How come is it still ambiguous if I have specified the table name.
Here is the table factors_apart_sa:
CREATE TABLE factors_apart_sa
(
factors_apar_sa_id bigserial NOT NULL,
surf_area integer,
sa_factor numeric(19,4) NOT NULL
)
Use a table alias:
CREATE OR REPLACE FUNCTION factors_apart_sa()
RETURNS TABLE(surf_area integer, sa_factor numeric) AS
$BODY$
BEGIN
RETURN QUERY SELECT f.surf_area, f.sa_factor FROM factors_apart_sa f;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
It is not a good idea to have the same names for a table and a function;
To call a function returnig set of rows place it in a FROM clause:
select f.*
from factors_apart_sa() f;

Postgres Stored procedure in select statement cannot get the datas

I am trying to get the data from the Database use function of select prison();.but i got error .Please advise me.
CREATE OR REPLACE FUNCTION prison() RETURNS refcursor AS $$
DECLARE
ref refcursor;
BEGIN
OPEN ref FOR SELECT round,ben_sc,ben_st FROM prison_issue;
RETURN ref;
END;
$$ LANGUAGE plpgsql;
and calling like this
select prison();
also i tried.but cannot executed the rows.
BEGIN;
SELECT prison();
-- Returns: <unnamed portal 2>
FETCH ALL IN "<unnamed portal 24>";
COMMIT;
There is no need for a PL/pgSQL function for this:
CREATE OR REPLACE FUNCTION prison()
RETURNS setof prison_issue
AS $$
SELECT * FROM prison_issue;
$$ LANGUAGE sql;
You also need to use:
select * from prison();
to retrieve the data, do not use select prison() (which only returns a single record, not multiple rows)
You didn't show us your definition of the table prison_issue if you don't want to return all columns you need something like this:
CREATE OR REPLACE FUNCTION prison()
RETURNS table (round integer, ben_sc text, ben_st text)
AS $$
SELECT SELECT round,ben_sc,ben_st FROM prison_issue;
$$ LANGUAGE sql;
You will need to adjust the part table (round integer, ben_sc text, ben_st text) to match the data type of the columns you select.
Below is an example code.I have assumed the data types.Replace with the real ones.
CREATE OR REPLACE FUNCTION prison() RETURNS TABLE(round numeric,ben_sc character varying,ben_st character varying) AS $$
BEGIN
RETURN QUERY SELECT p.round,p.ben_sc,p.ben_st FROM prison_issue p;
END;
$$ LANGUAGE plpgsql;

How to return multiple rows from PL/pgSQL function?

I have spent good amount of time trying to figure it out and I haven't been able to resolve it. So, I need your help please.
I am trying to write a PL/pgSQL function that returns multiple rows. The function I wrote is shown below. But it is not working.
CREATE OR REPLACE FUNCTION get_object_fields()
RETURNS SETOF RECORD
AS
$$
DECLARE result_record keyMetrics;
BEGIN
return QUERY SELECT department_id into result_record.visits
from fact_department_daily
where report_date='2013-06-07';
--return result_record;
END
$$ LANGUAGE plpgsql;
SELECT * FROM get_object_fields;
It is returning this error:
ERROR: RETURN cannot have a parameter in function returning set;
use RETURN NEXT at or near "QUERY"
After fixing the bugs #Pavel pointed out, also define your return type properly, or you have to provide a column definition list with every call.
This call:
SELECT * FROM get_object_fields()
... assumes that Postgres knows how to expand *. Since you are returning anonymous records, you get an exception:
ERROR: a column definition list is required for functions returning "record"
One way (of several) to fix this is with RETURNS TABLE (Postgres 8.4+):
CREATE OR REPLACE FUNCTION get_object_fields()
RETURNS TABLE (department_id int) AS
$func$
BEGIN
RETURN QUERY
SELECT department_id
FROM fact_department_daily
WHERE report_date = '2013-06-07';
END
$func$ LANGUAGE plpgsql;
Works for SQL functions just the same.
Related:
PostgreSQL: ERROR: 42601: a column definition list is required for functions returning "record"
I see more bugs:
first, a SET RETURNING FUNCTIONS call has following syntax
SELECT * FROM get_object_fields()
second - RETURN QUERY forwards query result to output directly. You cannot store this result to variable - it is not possible ever in PostgreSQL now.
BEGIN
RETURN QUERY SELECT ....; -- result is forwarded to output directly
RETURN; -- there will not be any next result, finish execution
END;
third - these simple functions is better to implement in SQL languages
CREATE OR REPLACE FUNCTION get_object_fields()
RETURNS SETOF RECORD AS $$
SELECT department_id WHERE ...
$$ LANGUAGE sql STABLE;
Here's one way
drop function if exists get_test_type();
drop type if exists test_comp;
drop type if exists test_type;
drop type if exists test_person;
create type test_type as (
foo int,
bar int
);
create type test_person as (
first_name text,
last_name text
);
create type test_comp as
(
prop_a test_type[],
prop_b test_person[]
);
create or replace function get_test_type()
returns test_comp
as $$
declare
a test_type[];
b test_person[];
x test_comp;
begin
a := array(
select row (m.message_id, m.message_id)
from message m
);
-- alternative 'strongly typed'
b := array[
row('Bob', 'Jones')::test_person,
row('Mike', 'Reid')::test_person
]::test_person[];
-- alternative 'loosely typed'
b := array[
row('Bob', 'Jones'),
row('Mike', 'Reid')
];
-- using a select
b := array (
select row ('Jake', 'Scott')
union all
select row ('Suraksha', 'Setty')
);
x := row(a, b);
return x;
end;
$$
language 'plpgsql' stable;
select * from get_test_type();
CREATE OR REPLACE FUNCTION get_object_fields()
RETURNS table (department_id integer)
AS
$$
DECLARE result_record keyMetrics;
BEGIN
return QUERY
SELECT department_id
from fact_department_daily
where report_date='2013-06-07';
--return result_record;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM get_object_fields()