当前位置:网站首页>PG 函数,根据表名生成对应的建表语句
PG 函数,根据表名生成对应的建表语句
2022-08-07 06:48:00 【高个子男孩】
CREATE OR REPLACE FUNCTION "ap"."generate_create_table_statement"("p_table_name" varchar)
RETURNS "pg_catalog"."text" AS $BODY$
DECLARE
v_table_ddl text;
column_record record;
BEGIN
FOR column_record IN
SELECT
b.nspname as schema_name,
b.relname as table_name,
a.attname as column_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) as column_type,
CASE WHEN
(SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
FROM pg_catalog.pg_attrdef d
WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) IS NOT NULL THEN
'DEFAULT '|| (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
FROM pg_catalog.pg_attrdef d
WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
ELSE
''
END as column_default_value,
CASE WHEN a.attnotnull = true THEN
'NOT NULL'
ELSE
'NULL'
END as column_not_null,
a.attnum as attnum,
e.max_attnum as max_attnum
FROM
pg_catalog.pg_attribute a
INNER JOIN
(SELECT c.oid,
n.nspname,
c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname ~ ('^('||p_table_name||')$')
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 2, 3) b
ON a.attrelid = b.oid
INNER JOIN
(SELECT
a.attrelid,
max(a.attnum) as max_attnum
FROM pg_catalog.pg_attribute a
WHERE a.attnum > 0
AND NOT a.attisdropped
GROUP BY a.attrelid) e
ON a.attrelid=e.attrelid
WHERE a.attnum > 0
AND NOT a.attisdropped
ORDER BY a.attnum
LOOP
IF column_record.attnum = 1 THEN
v_table_ddl:='CREATE TABLE '||column_record.schema_name||'.'||column_record.table_name||' (';
ELSE
v_table_ddl:=v_table_ddl||',';
END IF;
IF column_record.attnum <= column_record.max_attnum THEN
v_table_ddl:=v_table_ddl||chr(10)||
' '||column_record.column_name||' '||column_record.column_type||' '||column_record.column_default_value||' '||column_record.column_not_null;
END IF;
END LOOP;
v_table_ddl:=v_table_ddl||');';
RETURN v_table_ddl;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
边栏推荐
猜你喜欢
随机推荐
[Acwing Weekly Replay] The 63rd weekly match 20220806
Graphical LeetCode - 1408. String Matching in Arrays (Difficulty: Easy)
黑马程序员会话Cookie&Session
GBL210-ASEMI机箱电源适配器整流桥GBL210
A Pursuit of Temporal Accuracy in General Activity Detection TAG论文阅读笔记
【C语言】内存函数
Why NIO is more efficient than BIO
有 5nm 制程工艺的 MCU 吗?
Buffer and cache in memory
Hands-on Deep Learning - Computational Performance
[Problem record] A bloody case caused by filter, how to locate the problem of upstream link, problem troubleshooting and sharing of positioning ideas
VoLTE基础自学系列 | RTP及RTCP协议原理
LeetCode 628. 三个数的最大乘积
LeetCode 1163. The last substring lexicographically
bp神经网络 损失函数,bp神经网络参数优化
This beta version of Typora is expired
【小题练手】----平方矩阵
Taro 路由跳转预加载
devserver configuration
VoLTE基础自学系列 | 什么是VoLTE中的Silent Redial?它和CSFB什么关系?






![[Acwing Weekly Replay] The 63rd weekly match 20220806](/img/7f/1b2d1969edf17fd810eb2ea0613e58.png)

