oracle复制表sql

可以复制表的结构,也可以复制查询结果,有的时候需要小表,这样比较方面。

使用环境: oracle 10.2 ;scott  的dept表

表结构:

 
  

表数据:

 
  

常用sql的演示

--复制表结构 模板中原表名srctable 新建表名newtable
--1   复制全表结构
create table newtable as select *from srctable where 1<>1;
--说明 因为1肯定不等于1 所以子查询得到是个表结构

案例:新建一个dept1和dept表结构相同的空表

SQL> create table dept1 as select *from dept where 1<>1; 
 
Table created
 
SQL> select *from dept1;
 
DEPTNO DNAME          LOC
------ -------------- -------------

--2  复制全表结构和数据
create table newtable as select *from srctable;
--说明 也就是把原表的所有数据列出来,把整个表给newtable
--案例:创建一个表dept2和dept一样。

SQL> create table dept2 as select *from dept;
 
Table created
 
SQL> select *from dept2;
 
DEPTNO DNAME          LOC
------ -------------- -------------
    50 TRAN           BOSTON
    60 MARKET         
    10 ACCOUNTING     NEW YORK
    20 RESEARCH       DALLAS
    30 SALES          CHICAGO
    40 OPERATIONS     BOSTON
 
6 rows selected

剩下的就只给演示代码就好了,基本是一样的。

--3 复制部分的表结构,没有数据
create table newtable as select column1,..  from srctable where 1<>1;
--变化都在字段和where的语句了 找到规律很容易的
--案例

 
   
  1. SQL> create table dept3 as select deptno from dept where 1<>1; 
  2.   
  3. Table created 
  4.   
  5. SQL> select *from dept3; 
  6.   
  7. DEPTNO 
  8. ------ 

SQL> create table dept3 as select deptno from dept where 1<>1; Table created SQL> select *from dept3; DEPTNO ------

--4  复制部分表结构和相应的数据
create table newtable as select column1,... from  srctable;
--和2 ,3 比较一下子就记住了。。
--案例

 
   
  1. SQL> create table dept4 as select deptno from dept; 
  2.   
  3. Table created 
  4.   
  5. SQL> select *from dept4; 
  6.   
  7. DEPTNO 
  8. ------ 
  9.     10 
  10.     20 
  11.     30 
  12.     40 
  13.     50 
  14.     60 
  15.   
  16. rows selected 

SQL> create table dept4 as select deptno from dept; Table created SQL> select *from dept4; DEPTNO ------ 10 20 30 40 50 60 6 rows selected

--5把查询到的结果插入到其他表中
insert into table1(column1, column2, ....) select column1, column2, .... from table2;

这个要求2个表有一定的对应关系才行

案例;把刚才建立的空表dept1中插入 从dept中取得的数据

 
   
  1. SQL> insert into dept1(deptno,dname) select deptno,dname from dept; 
  2.   
  3. rows inserted 
  4.   
  5. SQL> select *from dept1; 
  6.   
  7. DEPTNO DNAME          LOC 
  8. ------ -------------- ------------- 
  9.     50 TRAN            
  10.     60 MARKET          
  11.     10 ACCOUNTING      
  12.     20 RESEARCH        
  13.     30 SALES           
  14.     40 OPERATIONS      
  15.   
  16. rows selected 

SQL> insert into dept1(deptno,dname) select deptno,dname from dept; 6 rows inserted SQL> select *from dept1; DEPTNO DNAME LOC ------ -------------- ------------- 50 TRAN 60 MARKET 10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS 6 rows selected

常用的也就是这种了。。

引用资料:http://database.51cto.com/art/201004/192790.htm