I have quite a few many-to-many relationships. To simplify the process of inserting data into the respective three tables, I have the below function that I adapt for the various M:M relationships, and it works like a charm. However, for situations when dealing with many new records, I would like to simplify the insert process even further.
At the moment I am using an .xls sheet with columns (and their order of sequence) corresponding to how they are written in the function (ex. surname, fname, email, phone, docutype, year, title, citation, digital, url, call_number, report_no, docu_description)
I then import that .xls incl. data to a new table in the database, and using Navicat's 'Copy as insert statement', and further copy & replacing the function-call to the statement, I end up with function call statements for all records in the table looking similar to this:
SELECT junction_insert_into_author_reportav ('Smith', 'Victoria',
some@email.com, NULL, 'Report', '2010', ' Geographical Place Names',
'Some citation, 'f', 'NULL', 'REP/63', NULL, NULL);
This works okay but I would like to reduce the steps involved even further if possible. For example by being able to pass the newly created table that I imported the .xls sheet into, as a parameter to the function -and then deleting the new table again after the insert statements in the function has run. I am just unsure how to do this, and if at all it is possible?
Here is an example of the function as it looks and works at the moment:
CREATE OR REPLACE FUNCTION junction_insert_into_author_reportav (
p_surname VARCHAR,
p_fname VARCHAR,
p_email VARCHAR,
p_phone TEXT,
p_docutype VARCHAR,
p_year int4,
p_title VARCHAR,
p_citation VARCHAR,
p_digital bool,
p_url TEXT,
p_call_no VARCHAR,
p_report_no VARCHAR,
p_docu_description VARCHAR
) RETURNS void AS $BODY$
DECLARE
v_authorId INT;
v_reportavId INT;
BEGIN
SELECT
author_id INTO v_authorId
FROM
author
WHERE
surname = p_surname
AND fname = p_fname;
SELECT
reportav_id INTO v_reportavId
FROM
report_av
WHERE
title = p_title;
IF
( v_authorId IS NULL ) THEN
INSERT INTO author ( surname, fname, email, phone )
VALUES
( p_surname, p_fname, p_email, p_phone ) RETURNING author_id INTO v_authorId;
END IF;
IF
( v_reportavId IS NULL ) THEN
INSERT INTO report_av ( docu_type, YEAR, title, citation, digital, url, call_number, report_no, docu_description )
VALUES
( p_docutype, p_year, p_title, p_citation, p_digital, p_url, p_call_no, p_report_no, p_docu_description ) RETURNING reportav_id INTO v_reportavId;
END IF;
INSERT INTO jnc_author_reportav
VALUES ( v_authorId, v_reportavId );
END;
$BODY$ LANGUAGE plpgsql VOLATILE COST 100