I created person table, then inserted 2 rows into it as shown below:
CREATE TABLE person (
id INT,
name VARCHAR(20),
age INT
);
INSERT INTO person (id, name, age)
VALUES (1, 'John', 27), (2, 'David', 32);
Then with an EXECUTE statement, I created my_func() with my_age and my_id parameter as shown below:
CREATE FUNCTION my_func(my_age INT, my_id INT) RETURNS VOID AS $$
BEGIN -- ↑↑↑↑↑↑ ↑↑↑↑↑
EXECUTE 'UPDATE person SET age = $1 WHERE id = $2' USING my_age, my_id;
END;
$$ LANGUAGE plpgsql;
Or:
CREATE FUNCTION my_func(my_age INT, my_id INT) RETURNS VOID AS $$
BEGIN
EXECUTE 'UPDATE person SET age = $1 WHERE id = $2' USING $1, $2;
END;
$$ LANGUAGE plpgsql;
Then, calling my_func() could update age of David to 56 as shown below:
postgres=# SELECT my_func(56, 2);
my_func
---------
(1 row)
postgres=# SELECT * FROM person;
id | name | age
----+-------+-----
1 | John | 27
2 | David | 56
(2 rows)
Next without an EXECUTE statement, I created my_func() with my_age and my_id parameter as shown below:
CREATE FUNCTION my_func(my_age INT, my_id INT) RETURNS VOID AS $$
BEGIN -- ↑↑↑↑↑↑ ↑↑↑↑↑
UPDATE person SET age = my_age WHERE id = my_id;
END;
$$ LANGUAGE plpgsql;
Or:
CREATE FUNCTION my_func(my_age INT, my_id INT) RETURNS VOID AS $$
BEGIN
UPDATE person SET age = $1 WHERE id = $2;
END;
$$ LANGUAGE plpgsql;
Then, calling my_func() could update age of David to 56 as shown below:
postgres=# SELECT my_func(56, 2);
my_func
---------
(1 row)
postgres=# SELECT * FROM person;
id | name | age
----+-------+-----
1 | John | 27
2 | David | 56
(2 rows)
So, what is the difference between the function with and without an EXECUTE statement?
With an EXECUTE statement, you can create
my_func()withageandidparameter which are the same names asageandidcolumn as shown below:Or:
Then, calling
my_func()could updateageofDavidto56as shown below:And without an
EXECUTEstatement, you can still createmy_func()withageandidparameter which are the same names asageandidcolumn as shown below:Or:
But, calling
my_func()above gets the error below: