sql中插入多行数据

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值

猜你喜欢

转载自blog.csdn.net/SQLplus111/article/details/83149985