Return result set using Weakly-typed cursor Variable - db2

CREATE or replace PROCEDURE return_result_set ( )
LANGUAGE SQL
SPECIFIC return_result_set
DYNAMIC RESULT SETS 1
rrs: BEGIN
DECLARE rs_cur CURSOR WITH RETURN
FOR SELECT *
FROM dummytable;
OPEN rs_cur;
END rrs
I can return result set using cursor by using above stored procedure, but I want to use cursor variable (Weakly-typed) in my stored procedure as the select query and table are going to vary based on a condition. Sample code here seems to be for different use case..
How to return a result set using a Cursor Variable?

Try this as is:
--#SET TERMINATOR #
SET SERVEROUTPUT ON#
BEGIN
DECLARE V_C1 CURSOR;
DECLARE V_I INT;
DECLARE PROCEDURE L_PROC(OUT LP_C1 CURSOR)
BEGIN
-- Dynamic cursor
--DECLARE V_STMT VARCHAR(128) DEFAULT 'SELECT * FROM (VALUES 1) T(I)';
--PREPARE V_S1 FROM V_STMT;
--SET LP_C1 = CURSOR FOR V_S1;
-- Static cursor
SET LP_C1 = CURSOR FOR SELECT * FROM (VALUES 1) T(I);
OPEN LP_C1;
END;
CALL L_PROC(V_C1);
FETCH V_C1 INTO V_I;
CALL DBMS_OUTPUT.PUT_LINE('I: ' || V_I);
CLOSE V_C1;
END#
SET SERVEROUTPUT OFF#

Related

Set value using select

I am new to using postgresql, I am trying to make a trigger that just inserts in the Employee table and also inserts in the Vacations table, but I don't know how to assign the values, I do it like that in sql but here I really don't know how
CREATE FUNCTION SP_InsertaVacacionesEmpleado() RETURNS TRIGGER
AS
$$
DECLARE _NumeroIdentificacion INTEGER;
DECLARE _FechaEntrada DATE;
BEGIN
SET _NumeroIdentificacion = SELECT NEW.NumeroIdentificacion FROM "Empleado"
SET _FechaEntrada = SELECT NEW.FechaEntrada FROM "Empleado"
INSERT INTO Vacaciones VALUES(_NumeroIdentificacion, _FechaEntrada, '', 0);
RETURN NEW;
END
$$
LANGUAGE plpgsql
As documented in the manual assignment is done using the := operator, e.g.:
some_variable := 42;
However to assign one or more variables from the result of a query, use select into, e.g.:
DECLARE
var_1 INTEGER;
var_2 DATE;
BEGIN
select col1, col2
into var_1, var_2
from some_table
...
However neither of that is necessary in a trigger as you can simply use the reference to the NEW record directly in the INSERT statement:
CREATE FUNCTION sp_insertavacacionesempleado()
RETURNS TRIGGER
AS
$$
BEGIN
INSERT INTO Vacaciones (...)
VALUES (NEW.NumeroIdentificacion, NEW.FechaEntrada , '', 0);
RETURN NEW;
END
$$
LANGUAGE plpgsql;
Note that you need to define a row level trigger for this to work:
create trigger ..
before insert on ...
for each row --<< important!
execute procedure sp_insertavacacionesempleado() ;

Fully replace a record with unbound PostgreSQL cursor

Is it possible to use unbound cursors to fully edit and replace a row in a table?
I'm using unbound cursors since the table is dynamically specified with a parameter, but I can't use the "UPDATE table SET column = value WHERE" syntax since the columns are unspecified.
CREATE OR REPLACE FUNCTION trim_table(in_table TEXT) AS $$
DECLARE
ref REFCURSOR;
current_row RECORD;
BEGIN
OPEN ref FOR EXECUTE 'SELECT * FROM '|| quote_ident(in_table);
LOOP
FETCH ref INTO current_row;
EXIT WHEN NOT FOUND;
current_row = my_row_function(current_row);
/*How can I replace my row here?*/
END LOOP;
CLOSE ref;
END
$$ LANGUAGE plpgsql;
All the example and answers I found show only how to update a single field and not the full record.
I think this code can help you in some ways :
select
string_agg('UPDATE '||table_schema||'.'||table_name||chr(13)||' SET '||column_name||' = TRIM('||column_name||')', '; '||chr(13)) into query
from information_schema.columns
where data_type in ('varchar', 'text')
and table_schema = 'your_schema'
and table_name = 'your_table_name';
execute query;
Put it in your procedure, modify it to your convenience, and you will no longer need this loop.

"INSERT INTO ... FETCH ALL FROM ..." can't be compiled

I have some function on PostgreSQL 9.6 returning a cursor (refcursor):
CREATE OR REPLACE FUNCTION public.test_returning_cursor()
RETURNS refcursor
IMMUTABLE
LANGUAGE plpgsql
AS $$
DECLARE
_ref refcursor = 'test_returning_cursor_ref1';
BEGIN
OPEN _ref FOR
SELECT 'a' :: text AS col1
UNION
SELECT 'b'
UNION
SELECT 'c';
RETURN _ref;
END
$$;
I need to write another function in which a temp table is created and all data from this refcursor are inserted to it. But INSERT INTO ... FETCH ALL FROM ... seems to be impossible. Such function can't be compiled:
CREATE OR REPLACE FUNCTION public.test_insert_from_cursor()
RETURNS table(col1 text)
IMMUTABLE
LANGUAGE plpgsql
AS $$
BEGIN
CREATE TEMP TABLE _temptable (
col1 text
) ON COMMIT DROP;
INSERT INTO _temptable (col1)
FETCH ALL FROM "test_returning_cursor_ref1";
RETURN QUERY
SELECT col1
FROM _temptable;
END
$$;
I know that I can use:
FOR _rec IN
FETCH ALL FROM "test_returning_cursor_ref1"
LOOP
INSERT INTO ...
END LOOP;
But is there better way?
Unfortunately, INSERT and SELECT don't have access to cursors as a whole.
To avoid expensive single-row INSERT, you could have intermediary functions with RETURNS TABLE and return the cursor as table with RETURN QUERY. See:
Return a query from a function?
CREATE OR REPLACE FUNCTION f_cursor1_to_tbl()
RETURNS TABLE (col1 text) AS
$func$
BEGIN
-- MOVE BACKWARD ALL FROM test_returning_cursor_ref1; -- optional, see below
RETURN QUERY
FETCH ALL FROM test_returning_cursor_ref1;
END
$func$ LANGUAGE plpgsql; -- not IMMUTABLE
Then create the temporary table(s) directly like:
CREATE TEMP TABLE t1 ON COMMIT DROP
AS SELECT * FROM f_cursor1_to_tbl();
See:
Creating temporary tables in SQL
Still not very elegant, but much faster than single-row INSERT.
Note: Since the source is a cursor only the first call succeeds. Executing the function a second time would return an empty set. You would need a cursor with the SCROLL option and move to the start for repeated calls.
This function does INSERT INTO from refcursor. It is universal for all the tables. The only requirement is that all columns of table corresponds to columns of refcursor by types and order (not necessary by names).
to_json() does the trick to convert any primitive data types to string with double-quotes "", which are later replaced with ''.
CREATE OR REPLACE FUNCTION public.insert_into_from_refcursor(_table_name text, _ref refcursor)
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
_sql text;
_sql_val text = '';
_row record;
_hasvalues boolean = FALSE;
BEGIN
LOOP --for each row
FETCH _ref INTO _row;
EXIT WHEN NOT found; --there are no rows more
_hasvalues = TRUE;
SELECT _sql_val || '
(' ||
STRING_AGG(val.value :: text, ',') ||
'),'
INTO _sql_val
FROM JSON_EACH(TO_JSON(_row)) val;
END LOOP;
_sql_val = REPLACE(_sql_val, '"', '''');
_sql_val = TRIM(TRAILING ',' FROM _sql_val);
_sql = '
INSERT INTO ' || _table_name || '
VALUES ' || _sql_val;
--RAISE NOTICE 'insert_into_from_refcursor(): SQL is: %', _sql;
IF _hasvalues THEN --to avoid error when trying to insert 0 values
EXECUTE (_sql);
END IF;
END;
$$;
Usage:
CREATE TABLE public.table1 (...);
PERFORM my_func_opening_refcursor();
PERFORM public.insert_into_from_refcursor('public.table1', 'name_of_refcursor_portal'::refcursor);
where my_func_opening_refcursor() contains
DECLARE
_ref refcursor = 'name_of_refcursor_portal';
OPEN _ref FOR
SELECT ...;

POSTGRESQL - FUNCTION SELECT + UPDATE

I need execute update for each return of the select, but I don't know how I can do it.
In firebird I have this code:
BEGIN
FOR
SELECT data_cadastro || ' ' || hora_cadastro as data_hora_cadastro,codigo_alteracao_convenio
FROM CC_ALTERACAO_CONVENIO
INTO:data_hora_cadastro,codigo_alteracao_convenio
DO
BEGIN
update CC_ALTERACAO_CONVENIO
set data_hora_cadastro = :data_hora_cadastro
where codigo_alteracao_convenio = :codigo_alteracao_convenio;
suspend;
END
END
I want change to function in postgresql.
I tried this, but not work because I don't know the syntax of postgresql of how can I do it.
CREATE OR REPLACE FUNCTION sim.ajuste_alteracao_convenio(OUT data_hora_cadastro character varying, OUT codigo_alteracao_convenio integer)
RETURNS SETOF record AS
$BODY$
DECLARE
v_data_hora_cadastro character varying;
v_codigo_alteracao_convenio INTEGER;
BEGIN
RETURN QUERY
SELECT data_cadastro || ' ' || hora_cadastro as data_hora_cadastro,codigo_alteracao_convenio
FROM sim.CC_ALTERACAO_CONVENIO
--loop
BEGIN
update sim.CC_ALTERACAO_CONVENIO
set data_hora_cadastro = v_data_hora_cadastro
where codigo_alteracao_convenio = v_codigo_alteracao_convenio;
END
--END LOOP;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
Could someone give me a direction of how can I solved this?
SOLVED
create type foo as (
data_hora_cadastro timestamp,
codigo_alteracao_convenio integer
)
CREATE OR REPLACE FUNCTION sim.ajuste_alteracao_convenio3()
RETURNS SETOF foo AS
$BODY$
DECLARE
r foo%rowtype;
BEGIN
FOR r IN SELECT data_cadastro || ' ' || hora_cadastro as data_hora_cadastro,codigo_alteracao_convenio FROM sim.CC_ALTERACAO_CONVENIO
LOOP
update sim.CC_ALTERACAO_CONVENIO
set data_hora_cadastro = r.data_hora_cadastro
where codigo_alteracao_convenio = r.codigo_alteracao_convenio;
RETURN NEXT r; -- return current row of SELECT
END LOOP;
RETURN;
END
$BODY$
LANGUAGE 'plpgsql' ;
Thank you all
Information is missing in the question, but it looks like all you need is a simple UPDATE with RETURNING:
UPDATE sim.cc_alteracao_convenio a
SET data_hora_cadastro = a.data_cadastro + a.hora_cadastro
RETURNING a.data_hora_cadastro, a.codigo_alteracao_convenio;
Assuming data_cadastro is data type date and hora_cadastro is data type time. Currently, you convert both to text, concatenate and cast back to timestamp. That's much more expensive than it needs to be. Just add both together: data_cadastro + hora_cadastro
The UPDATE itself looks like you are storing functionally dependent values redundantly. Once you've updated data_hora_cadastro you can drop data_cadastro and hora_cadastrocan.
If you positively need a function:
CREATE OR REPLACE FUNCTION sim.ajuste_alteracao_convenio3()
RETURNS TABLE (data_hora_cadastro timestamp
, codigo_alteracao_convenio integer) AS
$func$
UPDATE sim.cc_alteracao_convenio a
SET data_hora_cadastro = a.data_cadastro + a.hora_cadastro
RETURNING a.data_hora_cadastro, a.codigo_alteracao_convenio;
$func$ LANGUAGE sql; -- never quote the language name
You don't need to create a composite type, just use RETURNS TABLE() instead.
Or, if you need pre-UPDATE values:
Return pre-UPDATE Column Values Using SQL Only - PostgreSQL Version
this is what I do, it's an idea but may be it inspires you:
WITH insusu AS (
SELECT data_cadastro || ' ' || hora_cadastro
as data_hora_cadastro,codigo_alteracao_convenio
FROM sim.CC_ALTERACAO_CONVENIO
RETURNING id
)
update sim.CC_ALTERACAO_CONVENIO
set data_hora_cadastro =:data_hora_cadastro
from insusu;
select *
from insusu;
The Objetive is uses a with to determine with what data need work.

Update record of a cursor where the table name is a parameter

I am adjusting some PL/pgSQL code so my refcursor can take the table name as parameter. Therefore I changed the following line:
declare
pointCurs CURSOR FOR SELECT * from tableName for update;
with this one:
OPEN pointCurs FOR execute 'SELECT * FROM ' || quote_ident(tableName) for update;
I adjusted the loop, and voilĂ , the loop went through. Now at some point in the loop I needed to update the record (pointed by the cursor) and I got stuck. How should I properly adjust the following line of code?
UPDATE tableName set tp_id = pos where current of pointCurs;
I fixed the quotes for the tableName and pos and added the EXECUTE clause at the beginning, but I get the error on the where current of pointCurs.
Questions:
How can I update the record?
The function was working properly for tables from the public schema and failed for tables from other schemas (e.g., trace.myname).
Any comments are highly appreciated..
Answer for (i)
1. Explicit (unbound) cursor
EXECUTE is not a "clause", but a PL/pgSQL command to execute SQL strings. Cursors are not visible inside the command. You need to pass values to it.
Hence, you cannot use the special syntax WHERE CURRENT OFcursor. I use the system column ctid instead to determine the row without knowing the name of a unique column. Note that ctid is only guaranteed to be stable within the same transaction.
CREATE OR REPLACE FUNCTION f_curs1(_tbl text)
RETURNS void AS
$func$
DECLARE
_curs refcursor;
rec record;
BEGIN
OPEN _curs FOR EXECUTE 'SELECT * FROM ' || quote_ident(_tbl) FOR UPDATE;
LOOP
FETCH NEXT FROM _curs INTO rec;
EXIT WHEN rec IS NULL;
RAISE NOTICE '%', rec.tbl_id;
EXECUTE format('UPDATE %I SET tbl_id = tbl_id + 10 WHERE ctid = $1', _tbl)
USING rec.ctid;
END LOOP;
END
$func$ LANGUAGE plpgsql;
Why format() with %I?
There is also a variant of the FOR statement to loop through cursors, but it only works for bound cursors. We have to use an unbound cursor here.
2. Implicit cursor in FOR loop
There is normally no need for explicit cursors in plpgsql. Use the implicit cursor of a FOR loop instead:
CREATE OR REPLACE FUNCTION f_curs2(_tbl text)
RETURNS void AS
$func$
DECLARE
_ctid tid;
BEGIN
FOR _ctid IN EXECUTE 'SELECT ctid FROM ' || quote_ident(_tbl) FOR UPDATE
LOOP
EXECUTE format('UPDATE %I SET tbl_id = tbl_id + 100 WHERE ctid = $1', _tbl)
USING _ctid;
END LOOP;
END
$func$ LANGUAGE plpgsql;
3. Set based approach
Or better, yet (if possible!): Rethink your problem in terms of set-based operations and execute a single (dynamic) SQL command:
-- Set-base dynamic SQL
CREATE OR REPLACE FUNCTION f_nocurs(_tbl text)
RETURNS void AS
$func$
BEGIN
EXECUTE format('UPDATE %I SET tbl_id = tbl_id + 1000', _tbl);
-- add WHERE clause as needed
END
$func$ LANGUAGE plpgsql;
SQL Fiddle demonstrating all 3 variants.
Answer for (ii)
A schema-qualified table name like trace.myname actually consists of two identifiers. You have to
either pass and escape them separately,
or go with the more elegant approach of using a regclass type:
CREATE OR REPLACE FUNCTION f_nocurs(_tbl regclass)
RETURNS void AS
$func$
BEGIN
EXECUTE format('UPDATE %s SET tbl_id = tbl_id + 1000', _tbl);
END
$func$ LANGUAGE plpgsql;
I switched from %I to %s, because the regclass parameter is automatically properly escaped when (automatically) converted to text.
More details in this related answer:
Table name as a PostgreSQL function parameter