gpt4 book ai didi

sql - Postgres : create function in a particular database

转载 作者:行者123 更新时间:2023-11-29 11:56:18 25 4
gpt4 key购买 nike

代码:

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 和模式 public 中创建了一个函数。如何在特定数据库及其模式中创建函数?谢谢。

最佳答案

The above code created a function in the database postgres and 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

The first schema in the search path that exists is the default location for creating new objects.

终于回答了

How can I create a function in a particular database and it's schema?

连接到所需的数据库并明确指定模式名称:

CREATE FUNCTION my_schema.square_num(...and so on

或调整search_path以满足您的需求

更新 为清楚起见,我使用架构名称 postgres 来与原始帖子保持一致。使用 postgres 数据库和创建 postgres 模式都会让新用户感到困惑。默认的 postgres 数据库(可以随时从模板中重新创建)没有什么特别的(或系统的),名称 postgres 也没有为模式提供任何特殊属性。我只是将它用于 OP 以更轻松地重现示例(从他连接到 postgres 数据库这一事实可以清楚地看出,用户可能没有指定数据库名称,以操作系统用户 postgres 身份连接)。因此,为了演示 search_path 第一个值 $user 是如何被拾取的,我使用了与用户名相同的名称 ...

关于sql - Postgres : create function in a particular database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48007016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com