复制Oracle数据库的一张表,连带复制主键约束,字段说明以及字段默认值一起复制,sql该怎么写
时间: 2024-03-06 21:51:03 浏览: 237
要复制Oracle数据库中的一张表,包括主键约束、字段说明和字段默认值,可以使用以下SQL语句:
```sql
CREATE TABLE new_table AS
SELECT *
FROM old_table
WHERE 1=2;
DECLARE
v_constraint_name VARCHAR2(100);
v_column_name VARCHAR2(100);
BEGIN
FOR c IN (
SELECT constraint_name, column_name
FROM all_cons_columns
WHERE table_name = 'OLD_TABLE' AND constraint_name IN (
SELECT constraint_name
FROM all_constraints
WHERE table_name = 'OLD_TABLE' AND constraint_type = 'P'
)
)
LOOP
v_constraint_name := c.constraint_name;
v_column_name := c.column_name;
EXECUTE IMMEDIATE 'ALTER TABLE new_table ADD CONSTRAINT '||v_constraint_name||' PRIMARY KEY ('||v_column_name||')';
END LOOP;
END;
DECLARE
v_column_name VARCHAR2(100);
v_column_comment VARCHAR2(100);
BEGIN
FOR c IN (
SELECT column_name, comments
FROM all_col_comments
WHERE table_name = 'OLD_TABLE'
)
LOOP
v_column_name := c.column_name;
v_column_comment := c.comments;
EXECUTE IMMEDIATE 'COMMENT ON COLUMN new_table.'||v_column_name||' IS '''||v_column_comment||'''';
END LOOP;
END;
DECLARE
v_column_name VARCHAR2(100);
v_default_value VARCHAR2(100);
BEGIN
FOR c IN (
SELECT column_name, data_default
FROM all_tab_cols
WHERE table_name = 'OLD_TABLE' AND data_default IS NOT NULL
)
LOOP
v_column_name := c.column_name;
v_default_value := c.data_default;
EXECUTE IMMEDIATE 'ALTER TABLE new_table MODIFY ('||v_column_name||' DEFAULT '||v_default_value||')';
END LOOP;
END;
```
其中,new_table是新建的数据表名,old_table是要复制的数据表名。该SQL语句使用了三个PL/SQL块,分别用于复制主键约束、字段说明和字段默认值。注意,执行该SQL语句时需要先以管理员身份登录数据库。
阅读全文