zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

PostgreSQL UDF实现IF NOT EXISTS语法

postgresql 实现 not 语法 if exists UDF
2023-09-11 14:17:44 时间
背景

当对象存在时,不创建;当对象不存在时,创建。

在数据库中使用IF NOT EXISTS语法进行判断。

Syntax: 

CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ( [ 

有一些较老的版本,可能不支持IF NOT EXISTS语法,那么可以使用UDF实现类似的功能。

例如Greenplum:

create or replace function ddl_ine(sql text) returns int2 as $$ 

declare 

begin 

 execute sql; 

 return 0; -- 返回0表示正常 

 exception when duplicate_table then 

 raise notice %, SQLERRM; 

 return 1; -- 返回1表示已存在 

 when others then 

 raise notice %ERROR: % %create table error: %, chr(10), SQLERRM, chr(10), sql; 

 return 2; -- 返回2表示DDL其他错误 

end; 

$$ language plpgsql strict; 

测试
postgres=# select ctbl(create table c(id int)); 

NOTICE: Table doesnt have DISTRIBUTED BY clause -- Using column named id as the Greenplum Database data distribution key for this table. 

HINT: The DISTRIBUTED BY clause determines the distribution of data. Make sure column(s) chosen are the optimal data distribution key to minimize skew. 

CONTEXT: SQL statement "create table c(id int)" 

PL/pgSQL function "ctbl" line 3 at execute statement 

NOTICE: relation "c" already exists 

 ctbl 

------ 

(1 row) 

postgres=# select ctbl(create table e(id int)); 

NOTICE: Table doesnt have DISTRIBUTED BY clause -- Using column named id as the Greenplum Database data distribution key for this table. 

HINT: The DISTRIBUTED BY clause determines the distribution of data. Make sure column(s) chosen are the optimal data distribution key to minimize skew. 

CONTEXT: SQL statement "create table e(id int)" 

PL/pgSQL function "ctbl" line 3 at execute statement 

 ctbl 

------ 

(1 row) 

postgres=# select ctbl(create table e(id int9)); 

NOTICE: 

ERROR: type "int9" does not exist 

DETAIL: create table error: create table e(id int9) 

 ctbl 

------ 

(1 row) 

PostgreSQL的学习心得和知识总结(二十五)|语法级自上而下完美实现MySQL数据库的 字段默认值的自动插入更新 的实现方案 本人CSDN博主 孤傲小二~阿沐,本文《PostgreSQL的学习心得和知识总结(二十五)|语法级自上而下完美实现MySQL数据库的 字段默认值的自动插入更新 的实现方案》来自于我在CSDN的同名文档
PostgreSQL 12 preview - CTE 增强,支持用户语法层控制 materialized 优化 PostgreSQL , CTE , materialized , not materialized , push down PostgreSQL with 语法,能跑非常复杂的SQL逻辑,包括递归,多语句物化计算等。 在12以前的版本中,WITH中的每一个CTE(common table express),都是直接进行物化的,也就是说外层的条件不会推到CTE(物化节点)里
PostgreSQL允许带有命名参数的函数被使用位置或命名记号法调用。命名记号法对于有大量参数的函数特别有用,因为它让参数和实际参数之间的关联更明显和可靠。
PostgreSQL 10.1 手册_部分 II. SQL 语言_第 4 章 SQL语法_4.2. 值表达式 4.2. 值表达式 4.2.1. 列引用 4.2.2. 位置参数 4.2.3. 下标 4.2.4. 域选择 4.2.5. 操作符调用 4.2.6. 函数调用 4.2.7. 聚合表达式 4.2.8. 窗口函数调用 4.2.9. 类型转换 4.2.10. 排序规则表达式 4.2.11. 标量子查询 4.2.12. 数组构造器 4.2.13. 行构造器 4.2.14. 表达式计算规则
值表达式被用于各种各样的环境中,例如在SELECT命令的目标列表中、作为INSERT或UPDATE中的新列值或者若干命令中的搜索条件。