select * into destTbl from srcTbl insert into destTbl(fld1, fld2) select fld1, 5 from srcTbl
如上 destTbl 和 srcTbl 分别为两个表名。
以上两句都是将 srcTbl 的数据插入到 destTbl,但两句又有区别的:
- 第一句(select into from)要求目标表(destTbl)不存在,因为在插入时会自动创建。
- 第二句(insert into select from)要求目标表(destTbl)存在,由于目标表已经存在,所以我们除了插入源表(srcTbl)的字段外,还可以插入常量,如例中的:5。
以下两段代码摘自网友的博客,由于他也摘取了我的文章,所以相互摘录,供网友查看。
select into
--1.创建测试表 create TABLE Table1 ( a varchar(10), b varchar(10), c varchar(10), CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ( a ASC ) ) ON [PRIMARY] GO --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) GO --3.SELECT INTO FROM语句创建表Table2并复制数据 select a,c INTO Table2 from Table1 GO --4.显示更新后的结果 select * from Table2 GO --5.删除测试表 drop TABLE Table1 drop TABLE Table2
insert into select
--1.创建测试表 create TABLE Table1 ( a varchar(10), b varchar(10), c varchar(10), CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ( a ASC ) ) ON [PRIMARY] create TABLE Table2 ( a varchar(10), c varchar(10), d int, CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED ( a ASC ) ) ON [PRIMARY] GO --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) GO select * from Table2 --3.INSERT INTO SELECT语句复制表数据 Insert into Table2(a, c, d) select a,c,5 from Table1 GO --4.显示更新后的结果 select * from Table2 GO --5.删除测试表 drop TABLE Table1 drop TABLE Table2
ORACLE,用select into 复制一张表但是老说“缺失关键字”
1、直接建相同的表create table students_backup as select * from students;
2、直接建相同的表结构create table students_backup as select * from students where 1=2;
如果建好了表insert into students_backup select * from students