I just follow your solution. Make a minor change in the stored procedures INSERT statement.
The problem was regarding dynamic name of tables in stored procedure. There are different ways to solve it. I use quote_ident() function to resolve the issue. As per documentation of postgresql it is:
quote_ident ( text ) → text
Returns the given string suitably quoted to be used as an identifier in an SQL statement string. Quotes are added only if necessary (i.e., if the string contains non-identifier characters or would be case-folded). Embedded quotes are properly doubled
quote_ident('Foo bar') → "Foo bar"
Let's start the actual work.
- Creating tables(3) and appending test data
CREATE TABLE IF NOT EXISTS public.B3_HIST_2015
(
TranDate Date,
amount numeric(12,2)
);
INSERT INTO public.B3_HIST_2015(
TranDate, Amount)
VALUES ('01-Jan-2015', 2000), ('01-Feb-2015', 3000), ('01-Mar-2015', 4000);
CREATE TABLE IF NOT EXISTS public.B3_HIST_2016
(
TranDate Date,
amount numeric(12,2)
);
INSERT INTO public.B3_HIST_2016(
TranDate, Amount)
VALUES ('02-Apr-2016', 2000), ('03-May-2016', 3000), ('04-Jun-2016', 4000);
CREATE TABLE IF NOT EXISTS public.B3_HIST_2017
(
TranDate Date,
amount numeric(12,2)
);
INSERT INTO public.B3_HIST_2017(
TranDate, Amount)
VALUES ('12-Jul-2017', 2500), ('13-Aug-2017', 3007), ('14-Sep-2017', 4060);
CREATE TABLE IF NOT EXISTS public.TEMP1
(
TranDate Date,
amount numeric(12,2)
);
- Creating Stored Procedure
create or replace procedure public.SP_B3_HIST ()
language plpgsql
AS $$
declare
nametab TEXT := 'b3_hist_';
temptab TEXT :='';
startyr INTEGER := 2015;
lastyr INTEGER := 2017;
begin
while startyr <= lastyr loop
temptab = CONCAT(nametab, startyr);
execute 'INSERT INTO TEMP1(TranDate, Amount) (SELECT TranDate, Amount FROM ' || quote_ident(temptab) || ')';
startyr = startyr + 1;
END LOOP;
END; $$;
- Finally Calling the procedure for execution
call public.SP_B3_HIST ();
- Checking the data in table temp1
SELECT * FROM temp1;
Thank you.
EXECUTE. Check here: postgresql.org/docs/current/… Also, please end your statements in PL/pgSQL with a semicolon. Last, I cannot help but please, Postgres or PostgreSQL, not PostGRES - this is really triggering me.AS$$missing space betweenASand$$.