做数据库开发的过程中难免会遇到有表数据备份的,而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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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 ;
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 ;
Insert into Table2(a, c, d) select a,b,c from Table1;
commit ;
Insert into Table2 select * from table1;
commit ;
|
以上这些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
例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
create TABLE Table1
(
a varchar (10),
b varchar (10),
c varchar (10)
) ;
commit ;
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 ;
Create Table Table2 as select a,b,c From table1;
Commit ;
Create table table2 as select * From Table1;
Commit ;
drop table table1;
drop table table2;
commit ;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
create TABLE Table1
(
a varchar (10),
b varchar (10),
c varchar (10)
) ;
commit ;
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 ;
Select a,b,c into Table2 From table1;
Commit ;
Select * into table2 From Table1;
Commit ;
drop table table1;
drop table table2;
commit ;
|
到此这篇关于SQL Server之SELECT INTO 和 INSERT INTO SELECT案例详解的文章就介绍到这了
出处:
https://www.jb51.net/article/221227.htm