SELECT INTO 和 INSERT INTO SELECT


做數據庫開發的過程中難免會遇到有表數據備份的,而SELECT INTO……和INSERT INTO SELECT…… 這兩種語句就是用來進行表數據復制,下面簡單的介紹下:

1、INSERT INTO SELECT

語句格式:Insert Into Table2(column1,column2……) Select value1,value2,value3,value4 From Table1 或

       Insert Into Table2 Select * From Table1

說明:這種方式的表復制必須要求Table2是事先創建好的

例:

--1.創建表
create TABLE Table1
(
    a varchar(10),
    b varchar(10),
    c varchar(10)
) ;

create TABLE Table2
(
    a varchar(10),
    c varchar(10),
    d varchar(10)
);
commit;
--2.創建測試數據
Insert into Table1 values('','asds','90');
Insert into Table1 values('','asds','100');
Insert into Table1 values('','asds','80');
Insert into Table1 values('','asds',null);
commit;
--3.復制table1數據到table2中
Insert into Table2(a, c, d) select a,b,c from Table1;
commit;
--或,此種方式必須要求table2和table1的列數相等,而且類型兼容
Insert into Table2 select * from table1;
commit;
View Code

 以上這些sql在oracle和MS SqlServer中的語法是一樣的,可以通用.

2、SELECT INTO……

這種方式的語句可以在Table2不存在的時候進行表數據復制,編譯器會根據Table1的表結構自動創建Table2,Table2和Table1的結構基本上是一致的,但是如果已經存在Table2,則編譯器會報錯.

這種方式的語句在Oracle中和MS SqlServer中是有點差別的,,如下:

語句格式:

  Oracle:Create Table2 as Select column1,column2……From Table1 或 Create Table2 as Select * From Table1

  MS SqlServer:Select column1,column2…… into Table2 From Table1 或 Select * into Table2 From Table1

例:

--Oracle
--1.創建表
create TABLE Table1
(
    a varchar(10),
    b varchar(10),
    c varchar(10)
) ;

commit;
--2.創建測試數據
Insert into Table1 values('','asds','90');
Insert into Table1 values('','asds','100');
Insert into Table1 values('','asds','80');
Insert into Table1 values('','asds',null);
commit;
--3.復制table1數據到table2中
Create Table Table2 as select a,b,c From table1;
Commit;
--或(這兩種方式的sql只能應用一次)
Create table table2 as select * From Table1;
Commit;
--刪除表
drop table table1;
drop table table2;
commit;
View Code
--MS SqlServer
--1.創建表
create TABLE Table1
(
    a varchar(10),
    b varchar(10),
    c varchar(10)
) ;

commit;
--2.創建測試數據
Insert into Table1 values('','asds','90');
Insert into Table1 values('','asds','100');
Insert into Table1 values('','asds','80');
Insert into Table1 values('','asds',null);
commit;
--3.復制table1數據到table2中
Select a,b,c into Table2 From table1;
Commit;
--或(這兩種方式的sql只能應用一次)
Select * into table2 From Table1;
Commit;
--刪除表
drop table table1;
drop table table2;
commit;
View Code

 

  說明:由於比較懶,文章中的代碼引自http://www.cnblogs.com/freshman0216/archive/2008/08/15/1268316.html,稍作修改


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM