一次性插入多条sql语句的几种方法

时间:2023-03-09 03:45:53
一次性插入多条sql语句的几种方法

第一种:通过 insert select语句向表中添加数据

从现有表里面把数据插入到另外一张新表去
前提必须先有test_2表的存在,并且test_2表中的列的数据类型必须和test表里面列的数据类型一致,同时列的个数和顺序必须保持一致

如:

insert into test_2(name)
select name
from test ;

第二种:select into语句将现有表中的数据添加的新表中

student_2这个新表是执行查询语句的时候创建的,不能够预先存在

select name,age,sex

into student_2

from student

第三种:使用union关键字合并数据进行插入

union语句用于将两个不同的数据或查询结果组合成一个新的结果集,要求数据的个数,顺序,类型都一致

insert test('列名称')
select 'aa' union
select 'bb' union
select 'cc' ;

最后还有一个如何插入标识列的问题

select identity(int,1,1)

into 新表

from 原始表

-----插入标识列
select identity(int,1,1) as id,name
into test_2
from test;