Using postgreSQL 9.1.9, I have some SQL requests like this:
INSERT INTO "my_table" VALUES(10,'James','California');
Below a simplified table of the original names lookup table...
names
name_id name
--- -----
3 James
but in fact I don't have to enter (into "my_table") the text value provided by the SQL request (name of person, name of the state) but its corresponding ID located in another table (ex: names table)
Thanks to a previous post (execute sql inside plpgsql function) I learned how to create a function that returns the ID based on the name so that I can apply an INSERT with the name:
INSERT INTO my_table(my_table_id, name_id, state) VALUES (10, f_name_id('James'), 'California');
but I would prefer to execute it as a TRIGGER, so I just have to execute a simpler SQL:
INSERT INTO "my_table" VALUES(5,'James','test');
I created all the code below, but when I call the INSERT I get the error
invalid input syntax for integer
"James" (first INSERT command is expecting an integer, but we are providing text. The change text to integer is done later, by the f_id function in fill_table3 TRIGGER)
Some workaround? thanks in advance
--function to get the ID based on a name (lookup table)
CREATE OR REPLACE FUNCTION f_id(_table_name text,_name text, OUT _id int) AS
$func$
BEGIN
--EXECUTE 'select id FROM $1 WHERE sector = $2'
EXECUTE 'select id FROM '||_table_name||' WHERE sector = $2'
INTO _id
USING _table_name, _name;
END
$func$ LANGUAGE plpgsql;
--TRIGGER should do the INSERT operation
CREATE OR REPLACE FUNCTION fill_table3() RETURNS trigger AS
$func$
BEGIN
execute 'insert into '||TG_TABLE_NAME||' values ($1,f_id('||my_table||',$2),$3)';
END
$func$ LANGUAGE plpgsql;
CREATE TRIGGER fill_data
BEFORE INSERT
ON my_table
FOR EACH ROW
EXECUTE PROCEDURE fill_table3();