代码:
CREATE FUNCTION square_num(num integer)
RETURNS INTEGER AS $$
BEGIN
IF (num<0) THEN
RETURN 0;
END IF;
RETURN num*num;
END; $$
LANGUAGE PLPGSQL;
上面的代码在数据库postgres
和schema public
中创建了一个函数。如何在特定数据库及其架构中创建函数?谢谢。
上面的代码在数据库postgres和schema public中创建了一个函数。
不会。它在您从search_path
的第一个现有架构中连接到的数据库中创建功能。
例:
-bash-4.2$ psql t
psql (10.1)
Type "help" for help.
t=# create table tt();
CREATE TABLE
t=# select table_catalog,table_schema from information_schema.tables where table_name = 'tt';
table_catalog | table_schema
---------------+--------------
t | public
(1 row)
我在连接上定义了数据库名称t,因此在数据库t中创建了关系。我没有架构postgres,所以跳过$user
,接下来“默认”架构是public
:
t=# show search_path;
search_path
-----------------
"$user", public
(1 row)
现在:
t=# create schema postgres;
CREATE SCHEMA
t=# create table tt();
CREATE TABLE
看 - 没有关系已存在的错误,因为:
t=# select table_catalog,table_schema from information_schema.tables where table_name = 'tt';
table_catalog | table_schema
---------------+--------------
t | public
t | postgres
(2 rows)
函数创建遵循相同的规则,我使用表作为较短的语法...
阅读:https://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-PATH
存在的搜索路径中的第一个模式是用于创建新对象的默认位置。
终于回答了
如何在特定数据库及其架构中创建函数?
连接到所需的数据库并明确指定模式名称:
CREATE FUNCTION my_schema.square_num(...and so on
或调整search_path
以满足您的需求
更新为了清楚起见我使用架构名称postgres来遵守原始帖子。使用postgres数据库和创建postgres架构都会让新用户感到困惑。没有关于默认postgres数据库的特殊(或系统)(可以从模板中随时重新创建),postgres这个名称都没有为模式提供任何特殊属性。我只用OP来更容易重现这个例子(从他连接到postgres数据库的事实来看,用户可能没有指定数据库名称,连接为OS用户postgres)。因此,为了演示search_path
如何获得$user
的第一个值,我使用相同的名称作为用户名...