您好,欢迎访问一九零五行业门户网

当心 CREATE TABLE AS

对 dba 而言,create table as 可谓是家常便饭,顺手拈来。需不知该方式虽然简单,但疏忽也容易导致意想不到的问题。笔者前阵子就
对 dba 而言,create table as 可谓是家常便饭,顺手拈来。需不知该方式虽然简单,但疏忽也容易导致意想不到的问题。笔者前阵子就碰上了这样的事情。由于是对原表进行克隆,且数据存储在不同的表空间,因此毫不犹豫地使用了create table as,结果在运行package时,error...
--1、非空约束遗失
-->使用create table as 来创建对象
scott@cnmmbo> create table tb_dept as select * from dept where 1=0;
table created.
scott@cnmmbo> desc dept;
 name                                                  null?    type
 ----------------------------------------------------- -------- ------------------------------------
 deptno                                                not null number(2)
 dname                                                          varchar2(14)
 loc                                                            varchar2(13)
scott@cnmmbo> desc tb_dept;
 name                                                  null?    type
 ----------------------------------------------------- -------- ------------------------------------
 deptno                                                        number(2)
 dname                                                          varchar2(14)
 loc                                                            varchar2(13)
-->从上面的desc可以看出新创建的表少了非空约束
-->下面手动为其增加非空约束,增加后与原来的表是一致的。当然使用create table as时,索引是需要单独重建的。
scott@cnmmbo> alter table tb_dept modify (deptno not null); 
table altered.
scott@cnmmbo> drop table tb_dept;    -->删除刚刚穿件的表tb_dept
table dropped.
--2、存在非空约束时default约束遗失
-->下面为表dept的loc列添加非空约束,且赋予default值
scott@cnmmbo> alter table dept modify (loc default 'beijing' not null);
table altered.
-->为原始表新增一条记录
scott@cnmmbo> insert into dept(deptno,dname) select 50,'dev' from dual;
1 row created.
scott@cnmmbo> commit;
commit complete.
-->下面的查询可以看到新增记录50的loc为缺省值'beijing'
scott@cnmmbo> select * from dept;
    deptno dname          loc
---------- -------------- -------------
        10 accounting    new york
        20 research      dallas
        30 sales          chicago
        40 operations    boston
        50 dev            beijing
-->再次使用create table as来创建对象
scott@cnmmbo> create table tb_dept as select * from dept;
table created.       
-->从下面可知,由于列loc存在default值,,所以此时not null约束被同时赋予
scott@cnmmbo> desc tb_dept
 name                                                  null?    type
 ----------------------------------------------------- -------- ------------------------------------
 deptno                                                        number(2)
 dname                                                          varchar2(14)
 loc                                                  not null varchar2(13)
scott@cnmmbo> select * from tb_dept;
其它类似信息

推荐信息