I want to create a schema with with a name passed by variable. Example:
CREATE OR REPLACE FUNCTION test1("name" character varying)
  RETURNS void AS
'CREATE SCHEMA "name";'
  LANGUAGE 'sql' VOLATILE
  COST 100;
                Schema variables are created using the dr. schema() function.
One option, is to use QUOTENAME in a T-SQL script to construct a dynamic query. At least this way a syntax error will be thrown if the schema and table names are wrong: sql = @"declare @sql nvarchar(max)='SELECT Name FROM ' + QUOTENAME(@dbo) + '. [Members]'; select @sql; exec sp_executesql @sql;"; ...
Variables in data set schemas. By default, a schema variable, denoted by the type *, references an entire record, regardless of the data type of each field in the record. In this example, field1 , field2 , and field3 are included in the schema variable.
You could use plpgsql and than EXECUTE:
CREATE OR REPLACE FUNCTION test1("name" character varying)
RETURNS void AS
$$
BEGIN
    EXECUTE 'CREATE SCHEMA '|| quote_ident($1); -- security
    RETURN;
END;
$$
LANGUAGE plpgsql
VOLATILE
COST 20;
                        user search_path to change the default schema so you may easily add tables to it! and use format with %I to escape the schema name as identifier.
like this:
CREATE OR REPLACE FUNCTION test1("name" character varying)
RETURNS void AS
$$
BEGIN
    EXECUTE FORMAT('CREATE SCHEMA %I;', $1);
    EXECUTE FORMAT('SET search_path TO %I;', $1);
    CREATE TABLE table1(
    column1 integer
    );
    RETURN;
END;
$$
LANGUAGE plpgsql
VOLATILE
COST 20;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With