Yes, you can use EXECUTE and wrap it in FUNCTION. A function call allows you to pass parameters, and inside FUNCTION, you use string manipulation to modify the DDL statement. Finally, using EXECUTE in FUNCTION does this. Here is a simple example of a parameterized CREATE SEQUENCE statement ...
DROP FUNCTION sf.start_mc(integer); CREATE FUNCTION sf.start_mc(thefirst integer) RETURNS void AS $$ BEGIN EXECUTE format('CREATE SEQUENCE sf.mastercase START %s',thefirst); END; $$ LANGUAGE plpgsql;
We use the "format" of the string function to control the operator and include the parameter that was passed to the function. Of course, your SQL looks rather unusual, especially if you enable CREATE FUNCTION before you call it. This example comes from a data transfer job that I recently did. After CREATING a function, we used it like this:
DROP SEQUENCE sf.mastercase; -- the following uses the above function to set the starting value of a new sequence based on the last used -- in the widget table select sf.start_mc((select substring("widgetId",4)::integer + 1 from widgets where "widgetId" like 'MC-%' order by "widgetId" desc limit 1));
Note that the external SELECT does not select anything, it just makes room for a function call. The number that is passed as a parameter comes from the internal SELECT, which is enclosed in parentheses. A simpler call would be
select sf.start_mc(42);
You can wrap everything in a CREATEd FUNCTION. But this means that you are stuck in PostgreSQL and that you need to integrate your database schema and schema changes into your development process as a first-class citizen.
source share