SQL中一次插入多条数据
- 格式:pdf
- 大小:51.02 KB
- 文档页数:1
SQL中⼀次插⼊多条数据
SQL中insert⼀次可以插⼊⼀条数据,我们有三种⽅法可以⼀次性插⼊多条数据。
1.
语法:select 字段列表 into 新表 from 源表
注意事项:此种⽅法新表是系统⾃动创建,语句执⾏前不可以存在新表,并且新表只能保留源表的标识列特性,其他约束不能保留。
若只需要源表的数据结构,我们可以在语句中添加(top 0)
2.
语法:insert into ⽬的表 select 字段列表 from 源表
注意事项:此种⽅法⽬的表必须在语句执⾏前存在,并且每⼀列要与源表对应。
在此处还有⼀些有趣的问题,当我使⽤以下代码来插⼊多条数据时:
select top 0 * into newstudent from student
insert into newstudent select * from student
这⾥会发⽣这样的报错:
因为NewClass表中ClassId为标识列,所以我们不能插⼊值。
我们的解决办法如下:
select top 0 * into newstudent from student
set identity_insert newstudent on
insert into newstudent (classid,classname) select * from student
我们把newstudent 的标识列插⼊写为显⽰的,并且添加了列名字段便可以插⼊了。
之后我们再创建⼀个新的NewClass2:
select top 0 *into NewClass2 from MyClass
set identity_insert NewClass2 on
insert into NewClass2(ClassId,ClassName) select* from MyClass
此时还会报错,这是因为我们之前设置了newclass的标识列插⼊为on,我们必须先关闭后才可以往newclass2插⼊值,代码如下:
select top 0 *into NewClass2 from MyClass
set identity_insert newclass off
set identity_insert NewClass2 on
insert into NewClass2(ClassId,ClassName) select* from MyClass
⾄此我们解决了使⽤第⼆种⽅法⼀次插⼊多条数据。
3.
语法:insert into 表(字段列名) select 值 union select值