Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a schema with the name passed by variable

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;
like image 727
GVK Avatar asked Mar 05 '10 07:03

GVK


People also ask

What is the method function to create schema from a list variable?

Schema variables are created using the dr. schema() function.

How do I pass a dynamic schema name in SQL Server?

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;"; ...

What is schema variable?

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.


2 Answers

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;
like image 59
Frank Heikens Avatar answered Oct 19 '22 18:10

Frank Heikens


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;
like image 27
Elmer Avatar answered Oct 19 '22 18:10

Elmer