Oracle 構造與已知表結構相同的表問題

來源:互聯網
上載者:User

//構造一個與已知表就夠相同的表,我們常用的方法為:  
//create table t_name as  
//select col_name from t_exists  
//where 1=0;  
//這種構造方法,減少了我們的工作量,帶了很大的方便;  
//但是你知道嗎?這種構造表的方法,僅僅是構造表的結構與  
//已知表結構相同,其他的關於表、列的約束,列的預設值,注釋  
//等這些都沒有複製過來。  
create table student(  
       stu_no number(5),  
       stu_name varchar2(20),  
       sex char(1),  
       age number(3))  
--  
alter table student  
add constraint pk_stu primary key(stu_no);  
alter table student  
modify sex default 'M' 
add constraint ck_sex check(sex in('F','M'));  
comment on table student is '學生資訊表';  
comment on column student.stu_no is '學生學號';  
comment on column student.stu_name is '學生姓名';  
comment on column student.sex is '性別';  
comment on column student.age is '學生年齡';  
--  
SQL> desc student;  
Name     Type         Nullable Default Comments   
-------- ------------ -------- ------- --------   
STU_NO   NUMBER(5)                     學生學號   
STU_NAME VARCHAR2(20) Y                學生姓名   
SEX      CHAR(1)      Y        'M'     性別       
AGE      NUMBER(3)    Y                學生年齡   
--   
create table t_stu as 
select * from student  
where 1=0;  
--  
SQL> desc t_stu;  
Name     Type         Nullable Default Comments   
-------- ------------ -------- ------- --------   
STU_NO   NUMBER(5)    Y                           
STU_NAME VARCHAR2(20) Y                           
SEX      CHAR(1)      Y                           
AGE      NUMBER(3)    Y  
//從表結構,我們看到了,t_stu表只是複製了student表的結構,  
//而我們剛剛才為student表添加的primary key,default,comment,  
//全部都沒有複製過來。  
//如果你不僅想要構造表結構,而且還要向表中添加現存表中的資料,  
//你可以這樣寫:  
create table t_emp as 
select * from scott.emp  
order by sal  
where 1=1;//這個條件可有可無  
//執行個體:  
SQL> create table t_emp as 
  2  select * from scott.emp  
  3  where rownum<=5  
  4  order by sal;  
--  
SQL> select rownum,t.* from t_emp t;  
    ROWNUM EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO  
---------- ----- ---------- --------- ----- ----------- --------- --------- ------  
         1  7369 SMITH      CLERK      7902 1980-12-17     800.00               20  
         2  7521 WARD       SALESMAN   7698 1981-2-22     1250.00    500.00     30  
         3  7654 MARTIN     SALESMAN   7698 1981-9-28     1250.00   1400.00     30  
         4  7499 ALLEN      SALESMAN   7698 1981-2-20     1600.00    300.00     30  
         5  7566 JONES      MANAGER    7839 1981-4-2      2975.00               20 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.