I'm in the process of migrating our main db from SQL Server to PostgreSQL (while learning it in the process).
One of the things I need to move are a bunch of stored procedures, that generate tables with dynamic column names. That I got working with no problems. Thing is that some of those tables are later used to grab data to generate yet another table inside another stored procedure. Those subsequent procedures can take a long time to generate, 3-5 minutes sometime. While those are quite complex queries, I suspect this is due to the fact that the dynamically created tables contain no indexes, not even a primary key.
Below is a sample code for the least complex procedure. Could someone tell me how can I, within that procedure, add a primary key to the first column (material
) and then add extra index to the 6th column (total_open
)
CREATE OR REPLACE PROCEDURE sap_data.sp_ssa_po_final()
LANGUAGE plpgsql
AS $procedure$
DECLARE
month_next_5 varchar(3) := to_char(NOW() + interval '5 month', 'mon');
month_next_4 varchar(3) := to_char(NOW() + interval '4 month', 'mon');
month_next_3 varchar(3) := to_char(NOW() + interval '3 month', 'mon');
month_next_2 varchar(3) := to_char(NOW() + interval '2 month', 'mon');
month_next_1 varchar(3) := to_char(NOW() + interval '1 month', 'mon');
month_now varchar(3) := to_char(NOW(), 'mon');
month_prev_1 varchar(3) := to_char(NOW() - interval '1 month', 'mon');
month_prev_2 varchar(3) := to_char(NOW() - interval '2 month', 'mon');
month_prev_3 varchar(3) := to_char(NOW() - interval '3 month', 'mon');
month_prev_4 varchar(3) := to_char(NOW() - interval '4 month', 'mon');
month_prev_5 varchar(3) := to_char(NOW() - interval '5 month', 'mon');
month_prev_6 varchar(3) := to_char(NOW() - interval '6 month', 'mon');
sql_string varchar(3000) := '';
BEGIN
sql_string := 'CREATE TABLE sap_ssa_po_final AS SELECT
mat_no AS "material",
material_descr AS "material_description",
('||month_now||'+'||month_prev_1||'+'||month_prev_2||'+'||month_prev_3||'+'||month_prev_4||'+'||month_prev_5||'+'||month_prev_6||') as "open_till_'||month_now||'",
'||month_next_1||' AS "sum_'||month_next_1||'_qty",
'||month_next_2||' AS "sum_'||month_next_2||'_qty",
('||month_now||'+'||month_prev_1||'+'||month_prev_2||'+'||month_prev_3||'+'||month_prev_4||'+'||month_prev_5||'+'||month_prev_6||'+'||month_next_1||'+'||month_next_2||') as "total_open",
'||month_next_3||' AS "sum_'||month_next_3||'_qty",
'||month_next_4||' AS "sum_'||month_next_4||'_qty",
'||month_next_5||' AS "sum_'||month_next_5||'_qty",
NOW() as created_date
FROM v_ssa_po_summarised';
execute sql_string;
end;
$procedure$
;
I did try to google for answers but came up short. :(
execute sql_string;
.alter table add primary key(...)
andcreate index on ... (...)