I have this:
POSTGRES
/*THE PARAMETER in_test_id IS ONLY A TEST!!*/
CREATE OR REPLACE FUNCTION public.test_birt(in_test_id bigint DEFAULT NULL::bigint)
RETURNS refcursor AS
$BODY$
DECLARE
query text;
tcursor refcursor = 'tcursor';
BEGIN
query := 'SELECT * FROM MY_TABLE';
OPEN tcursor FOR execute query;
return tcursor;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
BIRT
DATASET --> MyDataset --> select * from test_birt(?::bigint)
Here the screenshots:
Report Design
Report Preview
I need that Birt shows the values of MY_TABLE!!. In this case, this table have one varchar field, with the values: TEST1, TEST2, TEST3.
The Birt Version is 3.2 and the postgres is 9.2.
NOTE The unique solution that i found was create a datatype and change the return datatype from my function, something like this:
RETURNS SETOF my_type AS
But I need that Bird can read this RefCursor.
You miss a FETCH statement.
When you call a function, then cursor "tcursor" is created (and opened). But nobody try to read from it. And without explicit support in Birt is impossible to call function and fetch data from cursor. You can try a hack - that can work or not (depends on implementation in Birt) - use following commands as source for dataset:
SELECT test_birt(?::bigint); FETCH ALL FROM tcursor;
I found link that shows so Birt didn't support it 5 years ago.
On second hand. In 9.2 you don't need to define own types for returning tables. You can use a table types - when you can return all columns or you can define output columns via TABLE keywords:
CREATE TABLE foo(a int, b int); -- automatically it defined type foo
CREATE OR REPLACE FUNCTION read_from_foo_1(_a int)
RETURNS SETOF foo AS $$
SELECT * FROM foo WHERE foo.a = _a;
$$ LANGUAGE SQL;
or
CREATE OR REPLACE FUNCTION read_from_foo_2()
RETURNS TABLE(a int, b int, c int) AS $$
SELECT a, b, a + b FROM foo;
$$ LANGUAGE SQL;
Related
I'm trying to create function which will accept ARRAY as INPUT and then return SETOF RECORD for each of the parameter in ARRAY.
I have table country_regions which consists of 3 Columns: id int, region_name TEXT, country_name TEXT;
My Functions code looks like this:
CREATE OR REPLACE FUNCTION search1(TEXT[])
RETURNS SETOF RECORD AS $$
DECLARE x RECORD;
BEGIN
FOR x IN
SELECT *
FROM company_regions
WHERE country_name = $1::TEXT
LOOP
RETURN NEXT x;
END LOOP;
END; $$
LANGUAGE plpgSQL;
This Function was created successfully, but when I try to call the function like this:
SELECT * FROM search1(ARRAY ['usa', 'canada']) AS search1(id int, region_name TEXT, country_name text)
it returns table with 0 rows in it.
Can someone tell me what am I doing wrong? I'm completely new to SQL, tried to find answer in other post but I still could not figure out the problem.
You try to compare text value versus text[].
CREATE OR REPLACE FUNCTION search1(text[])
RETURNS SETOF company_regions AS $$
BEGIN
RETURN QUERY SELECT * FROM company_regions
WHERE country_name = ANY($1);
END
$$ LANGUAGE plpgsql STABLE
Attention - functions like this are black box for optimizer. Usually is not too good (from performance perspective) using functions like envelops of one SQL statement. In complex query it can block some optimizations (Mainly if you forget to set correct flag of function - in this case STABLE).
I have a Postgres function which is returning a table:
CREATE OR REPLACE FUNCTION testFunction() RETURNS TABLE(a int, b int) AS
$BODY$
DECLARE a int DEFAULT 0;
DECLARE b int DEFAULT 0;
BEGIN
CREATE TABLE tempTable AS SELECT a, b;
RETURN QUERY SELECT * FROM tempTable;
DROP TABLE tempTable;
END;
$BODY$
LANGUAGE plpgsql;
This function is not returning data in row and column form. Instead it returns data as:
(0,0)
That is causing a problem in Coldfusion cfquery block in extracting data. How do I get data in rows and columns when a table is returned from this function? In other words: Why does the PL/pgSQL function not return data as columns?
To get individual columns instead of the row type, call the function with:
SELECT * FROM testfunction();
Just like you would select all columns from a table.
Also consider this reviewed form of your test function:
CREATE OR REPLACE FUNCTION testfunction()
RETURNS TABLE(a int, b int)
LANGUAGE plpgsql AS
$func$
DECLARE
_a int := 0;
_b int := 0;
BEGIN
CREATE TABLE tempTable AS SELECT _a, _b;
RETURN QUERY SELECT * FROM tempTable;
DROP TABLE tempTable;
END
$func$;
In particular:
The DECLARE key word is only needed once.
Avoid declaring parameters that are already (implicitly) declared as OUT parameters in the RETURNS TABLE (...) clause.
Don't use unquoted CaMeL-case identifiers in Postgres. It works, unquoted identifiers are cast to lower case, but it can lead to confusing errors. See:
Are PostgreSQL column names case-sensitive?
The temporary table in the example is completely useless (probably over-simplified). The example as given boils down to:
CREATE OR REPLACE FUNCTION testfunction(OUT a int, OUT b int)
LANGUAGE plpgsql AS
$func$
BEGIN
a := 0;
b := 0;
END
$func$;
Of course you can do this by putting the function call in the FROM clause, like Eric Brandstetter correctly answered.
However, this is sometimes complicating in a query that already has other things in the FROM clause.
To get the individual columns that the function returns, you can use this syntax:
SELECT (testfunction()).*
Or to get only the column called "a":
SELECT (testfunction()).a
Place the whole function, including the input value(s) in parenteses, followed by a dot and the desired column name, or an asterisk.
To get the column names that the function returns, you'll have to either:
check the source code
inspect the result of the function first, like so : SELECT * FROM testfunction() .
The input values can still come out of a FROM clause.
Just to illustrate this, consider this function and test data:
CREATE FUNCTION funky(a integer, b integer)
RETURNS TABLE(x double precision, y double precision) AS $$
SELECT a*random(), b*random();
$$ LANGUAGE SQL;
CREATE TABLE mytable(a integer, b integer);
INSERT INTO mytable
SELECT generate_series(1,100), generate_series(101,200);
You could call the function "funky(a,b)", without the need to put it in the FROM clause:
SELECT (funky(mytable.a, mytable.b)).*
FROM mytable;
Which would result in 2 columns:
x | y
-------------------+-------------------
0.202419687062502 | 55.417385618668
1.97231830470264 | 63.3628275180236
1.89781916560605 | 1.98870931006968
(...)
I want to pass the result of a subselect to a function
Say I've got an existing function that returns boolean
function report_can_edit which takes a report row type. I want to call this from another function which is passed an id for a report
( just a silly example to illustrate what I'm trying to do )
create or replace function report_can_edit(report report) returns boolean as $$
select true; -- Imagine this does some complicated stuff
$$ language sql stable;
create or replace function task_edit(task_report_id int) returns boolean as $$
select report_can_edit((select * from report where id = task_report_id))
$$ language sql stable;
This gives
ERROR: subquery must return only one column
Do I have to switch to plpgsql and select into a decared row type first? or is there a way to do this with an sql type function?
Try:
create or replace function task_edit(task_report_id int)
returns boolean as $$
select report_can_edit((select report from report where id = task_report_id))
$$ language sql stable;
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()
I know Oracle and PL/SQL
Compared to what I know about Oracle PL/SQL, I'm not very familiar with PostgreSQL's stored procedures and plpgsql. In Oracle, there are two types of callables:
Procedures. They can have IN, OUT and IN OUT parameters, but no return values
Functions. They can have IN, OUT and IN OUT parameters and they MUST return a value
But I'm new to plpgsql
I understand that in plpgsql, all stored procedures are considered functions. To my understanding, this means, they can (but don't have to) always return a value. Now I see on the documentation page, that I can also declare OUT parameters on functions, a thing that's not possible in Oracle. But I don't see an example or any clear statement about whether OUT parameters can be combined with return values. Neither can I see whether IN OUT parameters are possible.
So these are my questions:
Does plpgsql allow IN OUT parameters?
Does plpgsql allow OUT parameters to be combined with return values? Is this a common practice? Do you have examples for that?
IN and OUT are basically aliases for older syntax.
old way:
create function test(param int)
returns integer as
$$ select 1 $$
language sql;
equivalent:
create function test(in param int, out int)
as $$ select 1 $$
langauge sql;
What params do provide is type information which basically creates an anonymous type for your return:
create function test(in param, out int, out int)
as $$ select 1, 2 $$
langauge sql;
now you can write:
select * from test(1);
column1 | column2
---------+---------
1 | 2
Without the out params you would have have had to create a type or table that had two ints to cast the data to the right type:
create or replace function test(in a int)
returns record as
as $$ select 1, 2 $$
language sql;
^
select * from test(1);
ERROR: a column definition list is required
for functions returning "record"
... actually I should have searched a bit more myself. The answer is not far away on the documentations page:
http://www.postgresql.org/docs/current/static/sql-createfunction.html
if u specified out parameter, it means structure of your result
eg.
create function test(in param, out int, out int)
will return 2 columns of int. in postgre so far i know 2 way to do it.
1 return setof refcursor and use app to read it.
create function test(in param) RETURNS setof refcursor AS
declare result refcursor;
declare parameters refcursor;
begin
open result for select * from mytable;
return next result;
open parameter for select 11 as a, 22 as b;
return next parameters;
end;
2 use raise notice. In npgsql notice is an event which u can add handler to recieve.
raise notice 'my parameter = %', 11;
return query select * from mytable;
sorry that i didn't make it clear.
1 using 'out' parameter is to specifiy return query structure. u cannot return data + variable. 'out' in postgre doens't mean passing parameter reference.
2 if u want to return data + variable, either method 1 or 2.