前言
项目中有表复制的需求,而且是动态复制,即在存储过程里根据参数数组的值循环复制n张结构(约束、索引等)等一致的一组表,PostgreSQL提供了两种语法来进行表复制,分别是:
- CREATE TABLE AS
- CREATE TABLE LIKE
下面就通过一个例子来看看究竟哪一种更好或者说更符合我们的需求。
CREATE TABLE AS
首先看看CREATE TABLE AS的用法,在这之前结合一个具体的例子看看,我们需要复制的是这样一张表:
如上图所示,在PowerDesigner的物理模型(pdm)中我们可以看到这张表定义了主键和一个外键,再看看它的ddl语句:
drop table t_key_event_file_student;
/*==============================================================*/
/* Table: t_key_event_file_student */
/*==============================================================*/
create table t_key_event_file_student (
id SERIAL not null,
key_event_score_student_id INT4 not null,
file_name varchar(100) not null,
file_path varchar(100) not null,
constraint PK_T_KEY_EVENT_FILE_STUDENT primary key (id)
);
comment on table t_key_event_file_student is
'关键事件业务表(附件)';
comment on column t_key_event_file_student.id is
'主键';
comment on column t_key_event_file_student.key_event_score_student_id is
'关键事件录入ID';
comment on column t_key_event_file_student.file_name is
'附件文件名称';
comment on column t_key_event_file_student.file_path is
'附件文件路径';
alter table t_key_event_file_student
add constraint FK_T_KEY_EV_REF16_T_KEY_EV foreign key (key_event_score_student_id)
references t_key_event_score_student (id)
on

本文介绍了在PostgreSQL中如何动态复制表,包括使用`CREATE TABLE AS`和`CREATE TABLE LIKE`。通过示例展示了它们的差异,指出`CREATE TABLE LIKE`更接近需求,但无法复制外键约束。最终,通过自定义函数实现了动态复制表,包括创建新的序列和添加外键约束。
1476

被折叠的 条评论
为什么被折叠?



