A very simple function that copies data from one table to another in Postgresql can be implemented as follows:
CREATE OR REPLACE FUNCTION copiartabela(IN source VARCHAR, IN target VARCHAR) RETURNS VOID AS $$
BEGIN
EXECUTE 'insert into ' || target || ' select * from ' || source;
END;
$$ LANGUAGE PLPGSQL;
Function is declared with parameters source
and target
, respectively, the name of the source table and the name of the destination table.
The term IN
before the parameters defines that they are both input parameters, if it were OUT
would be output. The type of the parameters is text, represented by VARCHAR
. The excerpt RETURNS VOID
defines that the function does not return a value.
Within the function, the command EXECUTE
allows executing any dynamic query. The values passed for this command are a concatetion of values using the operator ||
that assemble a dynamic insertion.
The query generated by concatenation is a command INSERT
, inserting data into the target table from a SELECT
in the source table.
See a functional example of the function in **Sqlfiddle.**
Notes
Be careful not to confuse the terms Function (function), Procedure (procedure) and Trigger (trigger). Function is usually a routine that returns a value; Procedure is usually related to a routine that executes multiple commands and may or may not have output parameters; Trigger is a routine run when some action occurs in the database, for example, a record is inserted in a table.
In Postgresql there is not such a clear distribution between functions and procedures, as a function
can represent both one and the other.
If the tables have the same structure and information then why 2 tables?
– Clodoaldo Neto
Ask my teacher...
– LucasMotta