SQL数据插入

T-SQL中提供了多个将数据插入到表中的语句:insert values、insert select、insert exec、select into和Bulk insert;

1、  insert values

这是一种比较常用的插入数据方式,可以进行单条或者多条数据插入

首先创建一个表,然后进行数据插入操作 

create table test(

id int not null identity(1,1) primary key,

name nvarchar(100)

单条数据插入

insert into test(name) values('test1')

 

多行数据插入

insert into test(name) values('test2'),('test3'),('test4')

 

以上两种方式都可以省略表名后面的字段(不推荐这种方式),如下:

insert into test values('test1')

insert into test values('test2'),('test3'),('test4')

多行数据插入被作为一个原子性操作处理,即输入到表中的数据如果任意一行失败,则该语句不会插入到表中。

对于增强values子句,还可以将其作为表值构造函数以标准方式构建一个派生表,如下:

select * from (values

('001','test1'),

('002','test2'),

('003','test3')

)as test(id,name)

 

2、  insert select

insert select 语句和insert values语句类似,不同的是values子句不同,在这可以指定一个select查询,例如将刚才的数据复制到另外一个表test1中,首先创建test1表,结构与test相同

create table test1(

id int not null primary key,

name nvarchar(100)

)

执行插入语句

insert into test1

select ID,name from test

插入test1表结果如下,完全将test表中数据复制到test1中

 

删除test1中数据

truncate table test1

该数据插入方式中还可以使用union all进行多行数据插入

insert into test1

select '1','test1' union all

select '2','test2' union all

select '','test3'

查询test1表结果如下:

 

3、  insert exec

使用insert exec语句可以将存储过程或者动态SQL批处理的结果集插入到目标表中。

创建测试存储过程

create proc proc_Test @name as nvarchar(100)

as

select * from test where name like @name+'%'

go

测试执行结果

exec proc_Test 'test'

 

删除test1数据

truncate table test1

执行插入语句

insert into test1(id,name)

exec proc_test 'test'

查询test1表中数据

 

4、  select into

select into语句是一个非标准的T-SQL语句,它使用查询的结果创建并填充目标表。

使用下列语句可以将test中数据复制到temp的临时表中,temp表的结构和数据是基于test表的,该语句会将(列名、类型、是否为空、identity)属性和数据复制到目标表中,但是索引、约束、触发器和权限不会复制,如果目标表中需要这些需要重新创建。

select ID,name

into #temp

from test

查询#temp表,数据如下:

 

5、bulk insert

使用bulk insert语句将来自文件的数据插入到现有的一个表中。在语句中指定表、源文件和选项。可以指定多个选项,包括数据类型、字段终止符、行终止符和其他的文件选项

修改test表结构:

alter table test add address nvarchar(100) ,age int 

清空test表

truncate table test 

编辑本地文件,将下列蓝色字体数据保存在txt文件中,在SQL语句中指定该文件地址即可。

1,tom,北京市海淀区,20

2,sam,北京市朝阳区,23

3,amy,上海市浦东区,27

4,张三,河北省唐山市,28

5,李四,北京市海淀区,31

执行语句

  bulk insert dbo.test from 'C:\sqltest.txt'

  with(

  datafiletype='char',

  fieldterminator=',',

  rowterminator ='\n'

)

查询结果如下

 

posted @ 2016-07-13 23:27  Wǒ々啊申々  阅读(413)  评论(0编辑  收藏  举报