Create a temp table, loop and add data and select from it? query has no destination for result data - postgresql

I am creating a temp table, and am fetching data from multiple tables and inserting data into it. When I try to get the data back from the table I get an error
[42601] ERROR: query has no destination for result data Hint: If you want to discard the results of a SELECT, use PERFORM instead.
do
$$
DECLARE
sampleproductId varchar;
productIds text[] := array [
'abc1',
'abc2'
];
tId varchar;
DECLARE result jsonb;
DECLARE resultS jsonb[];
begin
CREATE TEMP TABLE IF NOT EXISTS product_temp_mapping
(
accountid int,
productUID varchar,
sampleproductId text
);
FOREACH sampleproductId IN ARRAY productIds
LOOP
tId := (select id
from product.product
where uid = sampleproductId);
INSERT into product_temp_mapping (accountid, productUID, sampleproductId)
select accountid, tId, sampleproductId
from product.accountproductmap
where productId = cast(tId as int);
END LOOP;
select * from product_temp_mapping;
end ;
$$;
Is this the right way to do it? This is the first time I am doing something with a temp table

Related

Postgres - function get the values from one query then insert as dynamic sql string

I am building a function on postgresql, basically send one id from one table then re-build the insert statement of that row and insert it as string column from another table.
I have this table, in insert_query I want to store the insert statement of one row, with his variables:
create table get_insert (tabname varchar(30), insert_query varchar(5000));
I want to store something like this on insert_query column:
Insert into baseball_table (code, name) select '01','Robet';
Currently my function is storing just this, which doesn't work since I need to store the real values:
INSERT INTO baseball_table(code,name) SELECT code,name FROM baseball_table WHERE id=1;
This is my function:
CREATE OR REPLACE FUNCTION get_values(
_id character varying
)
RETURNS boolean
LANGUAGE 'plpgsql'
VOLATILE PARALLEL UNSAFE
AS $function$
DECLARE v_id integer;
DECLARE sql_brand varchar;
BEGIN
sql_query'INSERT INTO baseball_table(code,name) SELECT code,name FROM core.brand WHERE id=' || v_id ||'
';
INSERT INTO core.clone_brand (tabname, insert_query)VALUES ('brand',sql_query);
RETURN true;
END;
$function$;
Which is the best way to get the real values without making variables of each column?
Regards
I want to get the way to get the real values without making variables of each column.

how to get the result of the select query and pass it as a input to delete query in Function Postgresql

CREATE OR REPLACE FUNCTION test(name VARCHAR (255))
RETURNS INTEGER AS
$BODY$
DECLARE
emp_id INTEGER;
BEGIN
SELECT employee.employee_id into emp_id from employee where first_name = name;
DELETE FROM employee WHERE employee_id = emp_id;
return emp_id;
END
$BODY$
LANGUAGE plpgsql;
when i call the function its deleting all the records in my employee table.
First store value in a variable for given input and these execute delete command with this variable and return this variable.
-- PostgreSQL
-- create table and store data
create table employee (emp_id int, name varchar(255));
insert into employee values (1, 'Rahul'), (2, 'Biswas'), (3, 'Shuva');
-- create function
CREATE OR REPLACE FUNCTION test(p_name varchar(255))
RETURNS INTEGER AS
$BODY$
DECLARE v_emp_id INTEGER;
BEGIN
SELECT e.emp_id into v_emp_id from employee e where e.name = p_name;
DELETE FROM employee WHERE emp_id = v_emp_id;
return v_emp_id;
END
$BODY$
LANGUAGE plpgsql;
-- execute function
select * from test('Rahul');
Please check this url https://dbfiddle.uk/?rdbms=postgres_11&fiddle=4c134787dafd8fe58b032d700168318d

Delete function storing the deleted record as json

I'm using a function in my Postgres and with this function, I want to delete a record using table and id and store the record as a JSON.
As you can imagine, I'm getting the table name as a parameter, but at that point, I don't know the name of the fields inside of my table. And I have:
create or replace function deletetable(_table text, _id int)
returns json as
$func$
declare
res json;
begin
execute format('SELECT json_to_recordset(::json) FROM ' || _table || ' WHERE id ' || id) into res;
-- HERE ONCE I GET THE RECORD AS JSON I HAVE TO INSERT IT IN MY TABLE
return res;
end
$func$ language plpgsql;
Well, my specific question is, how can I retrieve that information?
With my current function I get:
SELECT json_to_recordset(::json) FROM table
First create a log table:
create table logtable (
id serial primary key,
del_tname text not null,
del_ts timestamptz not null default now(),
del_rec jsonb
);
Your function should then look like this:
create or replace function deletetable(_table text, _id int)
returns jsonb as
$$
declare
res jsonb;
begin
execute format('with d as (delete from %I where id = %s returning *) '
'insert into logtable (del_tname, del_rec) '
'select %L, to_jsonb(d) from d returning del_rec',
_table, _id, _table) into res;
return res;
end
$$ language plpgsql;
Executing a select * from deletetable('tablename', 14); will delete your row, log it to logtable, and return the jsonb of the row.

How to write non parameterized function that returns table in postgresql

create or replace function demowhile_()
returns table (id integer,name varchar(50))
language 'plpgsql'
as $$
declare id integer;
declare name varchar(50);
begin
CREATE temporary TABLE demo_(id integer,name varchar(50));
CREATE temporary TABLE temp_ (id integer);
insert into temp_ (select id from demo);
while (select count(*) from temp_) <> 0
loop
id = (select top(1) id from temp_);
name = (select name from demo where id = id);
insert into demo_ values (id,name);
delete from temp_ where id = id;
end loop;
return query select id,name from demo;
end;
$$;
****while executing it is giving error like ****
select * from demowhile();
**ERROR: column reference "id" is ambiguous
LINE 1: insert into temp_ (select id,name from demo)
^
DETAIL: It could refer to either a PL/pgSQL variable or a table column.
QUERY: insert into temp_ (select id,name from demo)
CONTEXT: PL/pgSQL function demowhile() line 9 at SQL statement
SQL state: 42702**
demowhile_() returns table (id integer,name varchar(50) is basically the same thing as demowhile_(out id integer, out name varchar(50)) returns setof record
The id output column can be referenced directly from within the function. You've then also created a function variable named id. So when you assign a value to id, are you assigning to the output parameter or the declared variable? PG doesn't know, so you get that error.
And of course the simple solution is to give each a unique name.

PostgreSQL 9.3: Update tables contained in a view

I have a view which contains 3 tables. I want to update the each tables contained in the view.
Tables:
Table 1: test1
create table test1
(
id int,
name text,
city text
);
insert into test1 values(1,'Abc','xyz');
Table 2: test2
create table test2
(
id int,
name text,
city text
);
insert into test2 values(1,'bc','xz');
Table 3: test3
create table test3
(
id int,
name text,
city text
);
insert into test3 values(1,'Ac','yz');
View:
create view myview as select * from test1 union all select * from test2 union all select * from test3;
Note: I have a situation where I need to update the all tables city at once. So I have written a function
which does the update for a single table.
create or replace function updatefun(tablename text)
returns void as
$body$
Declare
query varchar;
Begin
query := 'Update '||tablename||'
set city = ''XXX''';
raise info '%',query;
execute query;
end;
$body$
Language plpgsql;
I have another table which contains the ViewId and ViewName.
create table viewdetails
(
ViewId int,
ViewName text
);
insert into viewdetails values(101,'myview');
Now I want to write another function to get all tables from the view and want to call the
function updatefun from this function to update all tables.
My try:
create or replace function fun1(vId int)
returns void as
$body$
declare
query varchar;
rec1 record;
rec2 record;
begin
DROP TABLE IF EXISTS temp_table1;
create temp table temp_table1(viewNames text);
query := 'insert into temp_table1 select ViewName from ViewDetails where ViewId = '|| vId ||'';
execute query;
for rec1 in select ViewNames from temp_table1 loop
for rec2 in SELECT Table_Name FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE WHERE View_Name = 'rec1' loop
select updatefun('rec2');
end loop;
end loop;
end;
$body$
language plpgsql;
Calling Function:
select fun1(101);
Checking view:
select * from myview;
Not getting why it is not getting updated??
This is incorrect:
select updatefun('rec2');
You want
perform updatefun(rec2);
without any quotes around rec2 otherwise it's interpreted as a literal, not the name of a variable.
Additionally rec2 should be of type TEXT, not RECORD.