Calling table function from procedure (pl sql) - function

I am having big trouble calling a function that returns a table from my procedure. I believe there is something wrong with my declaration so its not compiling. Here is my code.. the developer underlines with red the SELECT "D_ID" and from table "(IREL_FN (X))"; . And here is my code.
CREATE OR replace PROCEDURE Irrelevant_skata (x NUMBER)
AS
d_id T_ID_TABLE;
BEGIN
DECLARE
TYPE yo_table
IS
TABLE OF YO_TABLE;
YO_TABLE "(IREL_FN (X))"%TYPE;
id NUMBER;
BEGIN
SELECT "D_ID"
INTO yo_table
FROM TABLE "(IREL_FN (X))";
EXCEPTION
WHEN no_data_found THEN
dbms_output.Put_line('NO DATA FOUND');
END;
END irrelevant_skata;
And the function
CREATE OR replace FUNCTION Irel_fn (x IN NUMBER)
RETURN T_ID_TABLE
AS
id T_ID_TABLE;
BEGIN
BEGIN
SELECT Cast(MULTISET(SELECT "id"
FROM "somethingcopy"
WHERE "kati" IN (SELECT "auto"
FROM "ekeino"
WHERE "id" = x)) AS T_ID_TABLE)
INTO id
FROM dual;
RETURN id;
EXCEPTION
WHEN no_data_found THEN
dbms_output.Put_line('null');
END;
END irel_fn;

It's hard to answer without knowing what you're trying to do.
YO_TABLE "(IREL_FN (X))"%TYPE;
This doesn't make any sense. You can't declare a variable to be %type of a function. Looking up at YO_TABLE declaration, you write
DECLARE
TYPE yo_table
IS
TABLE OF YO_TABLE;
Huh? table declaration is table of same variable you're declaring?
And this:
SELECT "D_ID"
INTO yo_table
FROM TABLE "(IREL_FN (X))";
You don't need quotes when casting table, and the x in IREL_FN (X) is a formal parameter, you need to replace it with the actual value what you need to pass

create or replace
PROCEDURE IRRELEVANT_SKATA (INSID IN NUMBER) AS ID T_ID_TABLE ;
BEGIN
DECLARE
YO_TABLE T_ID_TABLE;
BEGIN
select ID
into YO_TABLE
from table(IREL_FN(INSID));
EXCEPTION
WHEN NO_DATA_FOUND THEN dbms_output.put_line('NO DATA FOUND');
END;
END IRRELEVANT_TWEET;
<-----------------------------FUNCTION---------------------------------->
create or replace
FUNCTION IREL_FN ( D_ID IN NUMBER ) RETURN T_ID_TABLE AS
ID T_ID_TABLE;
BEGIN
BEGIN
SELECT CAST(
MULTISET(
SELECT "Id"
FROM "SOMETHINGCOPY"
WHERE "KATI" = (SELECT "EKEINO" FROM "AUTO" WHERE "Id"=D_ID)
INTO ID
FROM DUAL;
return ID;
EXCEPTION
WHEN NO_DATA_FOUND THEN dbms_output.put_line('null');
END;
END IREL_FN;
I hope I helped :)

I am answering to your question marked as duplicate (the problem with exact fetch).
I rewrote your code in the following way, hope it helps. I makes the Irel_fn to be a pipelined function, however you can still write Cast multiset if you like , however you need to use type constructor as well.
create table auto(id number)
this table is instead of your source "AUTO" (so I could compile it).
create or replace type t_id as object (id number);
/
Create or replace type t_id_table is table of t_id;
/
create or replace FUNCTION Irel_fn (x IN NUMBER) RETURN T_ID_TABLE PIPELINED
as
BEGIN
for rec in (select id from auto where id=x)
loop
Pipe row (t_id(rec.id));
end loop;
return;
end;
/
create or replace procedure Irrelevant_skata (insid in NUMBER) is
bob t_id_table;
BEGIN
select t_id(id) bulk collect into bob from table(irel_fn(insid));
END;

Related

MySQL: Function not returning the correct integer

We have a question regarding a function returning the wrong integer-value in MySQL. We have checked that "booked_passengers" contains the right value, 0, and it works just fine when removing that variable, meaning just returning the integer 40. But as soon as we try to subtract "booked_passengers" from it, which still should end up returning 40, it does not work.
Including the code below.
Thanks in advance! :-)
CREATE FUNCTION calculateFreeSeats(flightnumber INT)
RETURNS INT
NOT DETERMINISTIC
BEGIN
DECLARE booked_passengers INT;
SELECT BOOKED_PASSENGERS INTO booked_passengers FROM FLIGHT WHERE (flightnumber = NR);
RETURN (40-booked_passengers);
END $$
When column name and local variable name interfere and there is no table alias then the variable is preferred. So your SELECT BOOKED_PASSENGERS ... selects variable value, not column value. Use
CREATE FUNCTION calculateFreeSeats(flightnumber INT)
RETURNS INT
READS SQL DATA
BEGIN
DECLARE booked_passengers INT;
SELECT FLIGHT.BOOKED_PASSENGERS INTO booked_passengers FROM FLIGHT WHERE (flightnumber = NR);
RETURN (40-booked_passengers);
END $$
From the other side the variable usage is obviously excess:
CREATE FUNCTION calculateFreeSeats(flightnumber INT)
RETURNS INT
READS SQL DATA
RETURN (SELECT 40 - BOOKED_PASSENGERS FROM FLIGHT WHERE flightnumber = NR LIMIT 1);

User defined function only returns NULL

I have this following MySQL code:
DELIMITER $$
CREATE FUNCTION durationInMinutes(id INT)
RETURNS INT DETERMINISTIC
BEGIN
DECLARE Minutes INT;
SET Minutes =
(SELECT TIME_TO_SEC(TIMEDIFF(timeDeparture, timeArrival)) FROM AirRoute
WHERE pk_id = id) / 60;
RETURN Minutes;
END$$
DELIMITER;
Basically, this function calculates the duration of a flight in minutes. The parameter is the id of the flight. For some reason though, this function always returns NULL. I even checked this:
SELECT (SELECT TIME_TO_SEC(TIMEDIFF(timeDeparture, timeArrival)) FROM AirRoute
WHERE pk_id = 925) / 60;
This does return the correct answer if I put id = 925, so there could be something wrong with the RETURN statement.
I suspect there is a column called id in the table. I always name parameters and local variables in a way to distinguish them from column names:
CREATE FUNCTION durationInMinutes (
in_id INT
)
RETURNS INT DETERMINISTIC
BEGIN
DECLARE out_Minutes INT;
SELECT out_Minutes := TIME_TO_SEC(TIMEDIFF(timeDeparture, timeArrival))
FROM AirRoute ar
WHERE ar.pk_id = in_id) / 60;
RETURN out_Minutes;
END$$
Ok, I solved it. This is my corrected code:
DELIMITER $$
CREATE FUNCTION durationInMinutes(id INT)
RETURNS INT DETERMINISTIC
BEGIN
RETURN (SELECT TIME_TO_SEC(TIMEDIFF(timeDeparture, timeArrival))
FROM AirRoute
WHERE pk_id = id / 60);
END$$
DELIMITER ;
Still, I really don't understand why it wasn't possible using a temp variable.

Trying to get Count single value from mysql stored procedure

I am trying to do a count in a mysql stored procedure but cant get the syntax right help1
delimiter//
create procedure get_count_workmen_type(
IN employee_payroll int,
OUT mycount int
)
begin
SELECT count(*) into mycount from workman
where employee_payroll = employee_payroll
end //
delimiter;
You should prefix your parameter names (personally I use "p_") to differentiate them from column names, etc. For example where employee_payroll = employee_payroll will always be true because it's comparing the column to itself.
Also you should add a semi-colon to the end of your select statement.
Putting those two changes together gives you something like this:
delimiter //
create procedure get_count_workmen_type(
IN p_employee_payroll int,
OUT p_mycount int
)
begin
SELECT count(*)
into p_mycount
from workman
where employee_payroll = p_employee_payroll;
end //
delimiter ;

How to return a table, rows or record from a function in PostgreSQL 9?

I have a table called person which has id,name,status and I want to return rows as a result of a function with 1 parameter (name).
Can anyone help me? Please make it easy, because im very noob in PostgreSQL.
This is my code from a normal function
create or replace function fn_list(vname varchar) returns void as $$
begin
SELECT id,name,status from usuario WHERE name= vname;
end;
$$ language plpgsql;
I know I'm returning a void function but how can I do if I want a list of rows?
I know that pipelined returns in Oracle does this, so I used that to find 'RETURN NEXT' from plpgsql:
http://www.postgresql.org/message-id/007b01c6dc31$ae395920$0a00a8c0#trivadis.com
Also on grokbase:
http://grokbase.com/t/postgresql/pgsql-performance/069kcttrfr/pipelined-functions-in-postgres
(Edit to add official documentation): http://www.postgresql.org/docs/9.2/static/plpgsql-control-structures.html
Killer, I will have to make use of this myself.
Editing one more time to add in some demo code (directly from postgresql.org documentation):
CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
INSERT INTO foo VALUES (1, 2, 'three');
INSERT INTO foo VALUES (4, 5, 'six');
CREATE OR REPLACE FUNCTION getAllFoo() RETURNS SETOF foo AS
$BODY$
DECLARE
r foo%rowtype;
BEGIN
FOR r IN SELECT * FROM foo
WHERE fooid > 0
LOOP
-- can do some processing here
RETURN NEXT r; -- return current row of SELECT
END LOOP;
RETURN;
END
$BODY$
LANGUAGE 'plpgsql' ;
SELECT * FROM getallfoo();
Using a loop to return the result of a query is slow and inefficient. The overhead of PL/pgSQL is not even required for this.
The best solution is:
create or replace function fn_list(vname varchar)
returns table(id integer, name text, status text)
as $$
SELECT id,name,status
from usuario
WHERE name= vname;
$$ language sql;
If PL/pgSQL is needed because some other procedural code needs to run before the query, then return query should be used instead of a loop:
create or replace function fn_list(vname varchar)
returns table(id integer, name text, status text)
as $$
begin
-- do some work....
return query
SELECT id,name,status
from usuario
WHERE name= vname;
end;
$$ language plpgsql;
Then call it using:
select *
from fn_list('Arthur');
Many answers here omit important parts of using functions. Here's an updated way of using functions in postgres (including declaration, variables, args, return values, and running). Below is an over-baked example of updating the tweet on the bottom right "blurb" with "hello world".
id (serial)
pub_id (text)
tweet (text)
1
abc
hello world
2
def
blurb
-- Optional drop if replace fails below.
drop function if exists sync_tweets(text, text);
create or replace function sync_tweets(
src_pub_id text, -- function arguments
dst_pub_id text
) returns setof tweets as -- i.e. rows. int, text work too
$$
declare
src_id int; -- temp function variables (not args)
dest_id int;
src_tweet text;
begin
-- query result into a temp variable
src_id := (select id from tweets where pub_id = src_pub_id);
-- query result into a temp variable (another way)
select tweet into src_tweet from tweets where id = src_id;
dest_id := (select id from tweets where pub_id = dst_pub_id);
update tweets set tweet=src_tweet where id = dest_id;
return query -- i.e. rows, return 0 with return int above works too
select * from tweets where pub_id in (src_pub_id, dst_pub_id);
end
$$ language plpgsql; -- need the language to avoid ERROR 42P13
-- Run it!
select * from sync_tweets('abc', 'def');
/*
Outputs
__________________________________________________
| id (serial) | pub_id (text) | tweet (text) |
|---------------|-----------------|----------------|
| 1 | abc | hello world |
| 2 | def | blurb |
--------------------------------------------------
*/

PostgreSQL: ERROR: $name$ is not a scalar variable

There is a function that returns 3 parameters one of which is a composite type:
CREATE OR REPLACE FUNCTION f1(
p_text text,
OUT result_status_id smallint,
OUT result_status_msg text,
OUT result_my_type my_type
)
RETURNS record AS
$BODY$
--body here
$BODY$
LANGUAGE 'plpgsql' VOLATILE SECURITY DEFINER
COST 100
The composite type my_type looks like following:
CREATE TYPE my_type AS
(d_real real,
d_int1 integer,
d_int2 integer,
d_int3 integer,
d_int4 integer,
d_int5 integer,
d_int6 integer,
d_int7 integer,
d_int8 integer,
d_int9 integer,
d_int10 integer,
d_bool boolean,
d_date date,
d_text text
);
There is another function f2 that calls function f1 in its body:
CREATE OR REPLACE FUNCTION f2(
p_text text
)
RETURNS record AS
$BODY$
DECLARE
l_status_id smallint;
l_status_msg text;
l_my_type my_type;
BEGIN
--some logic here
--this statement fails
SELECT * FROM f1(p_text) 'x'
INTO l_status_id, l_status_msg, l_my_type;
--logic continues here
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE SECURITY DEFINER
COST 100;
The problem is that when executing sql with the function I receive the following error:
ERROR: "l_my_type" is not a scalar variable
How may one get a composite type object from another function?
You are violating the rules. The manual:
where target can be a record variable, a row variable, or a
comma-separated list of simple variables and record/row fields.
A record or row variable cannot be part of multiple-item INTO list.
One way around this:
CREATE OR REPLACE FUNCTION f2(p_text text)
RETURNS record AS
$BODY$
DECLARE
r record;
l_status_id smallint;
l_status_msg text;
l_my_type my_type;
BEGIN
SELECT *
FROM f1(p_text) x -- don't single quote 'x'
INTO r;
l_status_id := r.result_status_id;
l_status_msg := r.result_status_msg;
l_my_type := r.result_my_type;
RETURN r; -- or whatever ..
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
There are more ways. Depends where you are going with this. I hardly ever return an anonymous record.
Composite types in tuples are one of those things which is supported partially and you run into odd issues (particularly with thins like storage but that's a story for another time). One way you could accomplish this is:
CREATE TYPE return_type_for_function AS (
result_status_id smallint,
result_status_msg text,
result_my_type my_type
);
CREATE FUNCTION myfunc(....) RETURNS return_type_for_function ....
This is the way I have always done it. This is a little more mature than using OUT variables.
Here's a trivial example:
or_examples=# create table rel_examples.tabletest (id int);
CREATE TABLE
or_examples=# create table comp_table_test (test rel_examples.tabletest);
CREATE TABLE
or_examples=# create function test(int) returns comp_table_test
immutable language sql as $$
select row(row($1))::comp_table_test; $$;
CREATE FUNCTION
or_examples=# select test(1);
test
---------
("(1)")
(1 row)
However, #Chris Travers has proposed an acceptable solution, in my case it was unfortunately not possible to introduce a new type for returning data from f1 function.
Nevertheless, one may call the function f1() in the function f2() and still get the data using the following syntax:
CREATE OR REPLACE FUNCTION f2(
p_text text
)
RETURNS record AS
$BODY$
DECLARE
l_status_id smallint;
l_status_msg text;
l_my_type my_type;
l_record record;
BEGIN
--some logic here
--this statement is okay now
l_record = f1(p_text);
l_status_id = l_record.result_status_id;
l_status_msg = l_record.result_status_msg;
l_my_type = l_record.result_my_type;
--logic continues here
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE SECURITY DEFINER
COST 100;
In your f2() function, you could do the select into a record variable and then extract what you need from it, e.g.:
CREATE OR REPLACE FUNCTION f2(p_text text )
RETURNS record AS
$BODY$
DECLARE
record_var record;
BEGIN
--this statement was failing
SELECT * FROM f1(p_text) INTO record_var;
SELECT l_my_type.result_my_type.d_int1; -- this should work
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE SECURITY DEFINER
COST 100;