Syntax error with Postgres FOR LOOP - postgresql

I have a problem in postgres function:
CREATE OR REPLACE FUNCTION linkedRepoObjects(id bigint)
RETURNS int AS $$
DECLARE catNumber int DEFAULT 0;
DECLARE cat RECORD;
BEGIN
WITH RECURSIVE children(categoryid,category_fk) AS (
SELECT categoryid, category_fk
FROM b2m.category_tab
WHERE categoryid = 1
UNION ALL
SELECT c1.categoryid,c1.category_fk
FROM b2m.category_tab c1, children
WHERE children.categoryid = c1.category_fk
)
FOR cat IN SELECT * FROM children LOOP
IF EXISTS (SELECT 1 FROM b2m.repoobject_tab WHERE category_fk = cat.categoryid) THEN
catNumber = catNumber +1
END IF;
END LOOP;
RETURN catNumber;
END;
$$ LANGUAGE 'plpgsql';
I've got error:
FEHLER: Syntax error near »FOR«
LINE 1: ...dren WHERE children.categoryid = c1.category_fk ) FOR $2 I...

The syntax error is because it is expecting the WITH ... to be followed by SELECT where it found FOR.
I haven't used WITH clauses in queries in plpgsql, but I'd try moving FOR cat IN to before the WITH, which is part of the query.

Try this:
CREATE OR REPLACE FUNCTION linkedRepoObjects(id bigint) RETURNS int AS
$$
DECLARE catNumber int DEFAULT 0;
DECLARE cat RECORD;
BEGIN
FOR cat IN
WITH RECURSIVE children(categoryid,category_fk) AS (
SELECT categoryid, category_fk
FROM b2m.category_tab
WHERE categoryid = 1
UNION ALL
SELECT c1.categoryid,c1.category_fk
FROM b2m.category_tab c1, children
WHERE children.categoryid = c1.category_fk
)
SELECT * FROM children
LOOP
IF EXISTS (SELECT 1 FROM b2m.repoobject_tab WHERE category_fk = cat.categoryid) THEN
catNumber = catNumber +1
END IF;
END LOOP;
RETURN catNumber;
END;
$$ LANGUAGE 'plpgsql';
I noticed your query hardly needs looping, just do this:
CREATE OR REPLACE FUNCTION linkedRepoObjects(id bigint) RETURNS int AS
$$
BEGIN
RETURN
(
SELECT COUNT(*) FROM b2m.repoobject_tab WHERE category_fk IN
(
WITH RECURSIVE children(categoryid,category_fk) AS
(
SELECT categoryid, category_fk
FROM b2m.category_tab
WHERE categoryid = 1
UNION ALL
SELECT c1.categoryid,c1.category_fk
FROM b2m.category_tab c1, children
WHERE children.categoryid = c1.category_fk
)
SELECT categoryid FROM children
)
);
END;
$$ LANGUAGE 'plpgsql';

Related

Cursor not found

i have created procedure, inside used cursor to update the some data, while calling the procedure it's getting the error.
create or REPLACE PROCEDURE bal_upd(p_id int) as
$$
DECLARE rc record;
----- cursor
bal_upd1 CURSOR (p_id int)
for
select * from tbal where custid = p_id;
begin
open bal_upd1 (p_id);
loop
FETCH bal_upd1 into rc;
exit when not found;
update t_trans set balance = balance + rc.trans;
COMMIT;
end loop;
close bal_upd1;
end;
$$ LANGUAGE plpgsql;
call bal_upd(1)
ERROR: cursor "bal_upd1" does not exist
CONTEXT: PL/pgSQL function bal_upd(integer) line 12 at FETCH
SQL state: 34000
create or REPLACE PROCEDURE bal_upd(p_id int) as
$$
DECLARE rc record;
----- cursor
bal_upd1 CURSOR (p_id int)
for
select * from tbal where custid = p_id;
begin
open bal_upd1 (p_id);
loop
FETCH bal_upd1 into rc;
exit when not found;
update t_trans set balance = balance + rc.trans;
COMMIT;
end loop;
close bal_upd1;
end;
$$ LANGUAGE plpgsql;
call bal_upd(1)
ERROR: cursor "bal_upd1" does not exist
CONTEXT: PL/pgSQL function bal_upd(integer) line 12 at FETCH
SQL state: 34000
You don't need a function or a loop for that:
UPDATE t_trans
SET balance = t_trans.balance + t.trans
FROM (SELECT sum(trans) AS trans
FROM tbal
GROUP BY custid) AS t
WHERE t_trans.custid = t.custid;
I tried, failed. I just found just use for loop (implicit cursor) is far more simple.
BEGIN;
CREATE temp TABLE tbal (
custid bigint
, trans numeric
);
INSERT INTO tbal VALUES (1 , 1);
INSERT INTO tbal VALUES (1 , 2);
CREATE temp TABLE t_trans (
custid bigint
, balance numeric
);
INSERT INTO t_trans VALUES (1 , 10);
COMMIT;
CREATE OR REPLACE PROCEDURE bal_upd (bigint)
AS $func$
DECLARE
rc record;
BEGIN
FOR rc IN
SELECT
*
FROM
tbal
WHERE
custid = $1 LOOP
RAISE NOTICE 'custid: %, trans: % ' , rc.custid , rc.trans;
UPDATE
t_trans ta
SET
balance = balance + (rc.trans)
WHERE
ta.custid = (rc.custid);
END LOOP;
END;
$func$
LANGUAGE plpgsql;
Then call it. CALL bal_upd(1);

How to compare two table value using if condition in function of Postgres

create or replace function trace.get_latest_exception_custom_msg(id varchar)
returns varchar
language plpgsql
as $$
declare
msg varchar ;
begin
perform t1.message, t1.created_time from table_1 t1 where t1.id = id order by t1.created_time desc limit 1;
perform t2.message, t2.created_time from table_2 t2 where t2.id = id order by t2.created_time desc limit 1;
if date(t1.created_time ) >= date(t2.created_time) then msg= t1.message;
elsif d date(t1.created_time ) < date(t2.created_time) then msg= t1.message;
else msg =t1.message;
end if;
return msg;
end;
while i call this function it give error ERROR: missing FROM-clause entry for table "t_1
You need to store the result of the two SELECT queries into variables in order to be able to be able to use them in an IF statement.
Your IF statement is also a bit confusing as all three parts assign the same value to msg. I assume that you want to use t2.message at least in one case.
create or replace function trace.get_latest_exception_custom_msg(p_id varchar)
returns varchar
language plpgsql
as
$$
declare
t1_msg varchar;
t1_created date;
t2_msg varchar;
t2_created date;
msg varchar;
begin
select t1.message, t1.created_time::date
into t1_msg, t1_created
from table_1 t1
where t1.id = p_id
order by t1.created_time desc
limit 1;
select t2.message, t2.created_time::date
into t2_msg, t2_created
from table_2 t2
where t2.id = p_id
order by t2.created_time desc
limit 1;
if t1_created >= t2_created then
msg := t1_msg;
elsif t1_created < t2_created then
msg := t2_msg; --<< ???
else
-- this can only happen if one (or both) of the DATEs is NULL.
msg := t1_msg;
end if;
return msg;
end;
$$

Postgresql: UPDATE before INSERT function

I have problem when create function for trigger. I want to UPDATE inserted value BEFORE INSERT data to DB.
My code look like this:
CREATE OR REPLACE FUNCTION test_func()
RETURNS TRIGGER AS
$$
DECLARE cnt INTEGER;
BEGIN
cnt := COUNT(*) FROM sample_tbl WHERE id = NEW.id AND created_date = NEW.created_date;
NEW.current_order := cnt + 1; // I want to set value of sample_tbl.current_order automatically
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER test_trigger
BEFORE INSERT
ON test_tbl
FOR EACH ROW
EXECUTE PROCEDURE test_func();
I inserted data then IDE said:
control reached end of trigger procedure without RETURN
Where: PL/pgSQL function test_func()
The error says that you must return something from the Trigger ( either NEW or NULL )
There's no Trigger needed for this. A simple View using this select query will give you the required result
--create or replace view sample_view as
select t.id, t.created_date,
row_number() OVER ( partition by id,created_date order by id ) as current_order
FROM sample_tbl t;
This will exactly match the records if updated using a Trigger
CREATE OR REPLACE FUNCTION test_func()
RETURNS TRIGGER AS
$$
DECLARE cnt INTEGER;
BEGIN
select COUNT(*) INTO cnt FROM sample_tbl WHERE id = NEW.id
AND created_date = NEW.created_date;
NEW.current_order := cnt + 1;
RETURN NEW; --required
END
$$ LANGUAGE plpgsql;
Demo
Your trigger function is just missing RETURN NEW; statement:
CREATE OR REPLACE FUNCTION test_func()
RETURNS TRIGGER AS
$$
DECLARE cnt INTEGER;
BEGIN
cnt := COUNT(*) FROM sample_tbl WHERE id = NEW.id AND created_date = NEW.created_date;
NEW.current_order := cnt + 1;
RETURN NEW;
END
$$ LANGUAGE plpgsql;

I tried to execute a query and gave me an error and i can't understand why?

DROP FUNCTION IF EXISTS top_5(customers.customerid%TYPE, products.prod_id%TYPE, orderlines.quantity%TYPE) CASCADE;
CREATE OR REPLACE FUNCTION top_5(c_id customers.customerid%TYPE, p_id products.prod_id%TYPE, quant orderlines.quantity%TYPE)
RETURNS orders.orderid%TYPE AS $$
DECLARE
top_prod CURSOR IS
SELECT inv.prod_id
FROM inventory AS inv, products AS prod
WHERE inv.prod_id=prod.prod_id
ORDER BY inv.quan_in_stock desc, inv.sales
limit 5;
ord_id orders.orderid%TYPE;
ord_date orders.orderdate%TYPE:= current_date;
ordln_id orderlines.orderlineid%TYPE:=1;
BEGIN
SELECT nova_orderid() INTO ord_id;
INSERT INTO orders(orderid, orderdate,customerid,netamount,tax,totalamount) VALUES(ord_id,ord_date,c_id,0,0,0);
PERFORM compra(c_id, p_id, 1::smallint, ord_id, ordln_id, ord_date);
IF (p_id = top_prod) THEN
UPDATE orders
SET totalamount = totalamount - (totalamount*0.2)
WHERE ord_id = (SELECT MAX(ord_id) FROM orders);
END IF;
END;
$$ LANGUAGE plpgsql;
I have the following code and when i try to execute this
SELECT top_5(1,1,'2');
i have this error
ERROR: operator does not exist: integer = refcursor
LINE 1: SELECT (p_id = top_prod)
You need to get the 'prod_id' value from the cursor 'top_prod'.
You cannot compare two types.
Try this,
DECLARE
top_prod_id top_prod%ROWTYPE;
BEGIN
OPEN top_prod;
LOOP
FETCH top_prod INTO top_prod_id;
EXIT WHEN top_prod %NOTFOUND;
IF (p_id = top_prod_id) THEN
UPDATE orders
SET totalamount = totalamount - (totalamount*0.2)
WHERE ord_id = (SELECT MAX(ord_id) FROM orders);
END IF;
END LOOP;
CLOSE top_prod;
END;

PostgreSQL: Return JSON from function using language plpgsql

I have the following table with two fields:
create table tbl_jtest
(
cola int,
colb varchar(10)
);
Inserting some records:
insert into tbl_jtest values(1,'a');
insert into tbl_jtest values(2,'b');
insert into tbl_jtest values(3,'c');
insert into tbl_jtest values(4,'d');
Function:
CREATE OR REPLACE FUNCTION ufn_jtest1(pcola int)
RETURNS json AS
$$
BEGIN
IF pcola = 1
THEN
RETURN QUERY SELECT to_json(a.cola) FROM tbl_jtest a;
ELSE
RETURN QUERY SELECT to_json(a.colb) FROM tbl_jtest a;
END IF;
END;
$$ LANGUAGE plpgsql;
Error details:
ERROR: cannot use RETURN QUERY in a non-SETOF function LINE 7:
RETURN QUERY SELECT to_json(a.cola) FROM tbl_jtest a;
^
I have tried the followings:
Try 1:
PERFORM to_json(a.cola) FROM tbl_jtest a;
Try 2:
RETURN QUERY PERFORM to_json(a.cola) FROM tbl_jtest a;
Or are you looking for something like this?
create table tbl_jtest
(
cola int,
colb varchar(10),
colc varchar(10)
);
insert into tbl_jtest values(1,'a','e');
insert into tbl_jtest values(2,'b','f');
insert into tbl_jtest values(3,'c','g');
insert into tbl_jtest values(4,'d','h');
SELECT * FROM tbl_jtest;
CREATE OR REPLACE FUNCTION ufn_jtest1(pcola int)
RETURNS table (j json) AS
$$
BEGIN
IF pcola = 1
THEN
RETURN QUERY SELECT row_to_json(a) FROM (SELECT cola, colb FROM tbl_jtest) a;
ELSE
RETURN QUERY SELECT to_json(a) FROM (SELECT colb, colc FROM tbl_jtest) a;
END IF;
END;
$$ LANGUAGE plpgsql;
Test 1
SELECT ufn_jtest1(1);
Output 1
ufn_jtest1
1 {"cola":1,"colb":"a"}
2 {"cola":2,"colb":"b"}
3 {"cola":3,"colb":"c"}
4 {"cola":4,"colb":"d"}
Test2
SELECT ufn_jtest1(2);
Output2
ufn_jtest1
1 {"colb":"a","colc":"e"}
2 {"colb":"b","colc":"f"}
3 {"colb":"c","colc":"g"}
4 {"colb":"d","colc":"h"}
are loking for such?:
CREATE OR REPLACE FUNCTION ufn_jtest2(pcola int)
RETURNS table (j json) AS
$$
BEGIN
IF pcola = 1
THEN
RETURN QUERY SELECT to_json(a.cola) FROM tbl_jtest a;
ELSE
RETURN QUERY SELECT to_json(a.colb) FROM tbl_jtest a;
END IF;
END;
$$ LANGUAGE plpgsql;