复制数据--bulk insert语句和bcp实用工具

bulk insert语句和bcp实用工具用于在SQL SERVER 数据库和数据文件之间复制数据.

(ps:关于导入和导出数据的更多使用方法,可以参考《sql server联机丛书》的 “管理 SQL Server ”-->“导入和导出数据”章节)

1)bulk insert语句

bulk insert以用户指定的格式复制一个数据文件至数据库表或视图中。

下面的例子会将authors.txt的内容导入数据库表中pubs..authors:

BULK INSERT pubs..authors FROM 'd:/tmp/authors.txt'
WITH (
   DATAFILETYPE = 'char',
   FIELDTERMINATOR = ',',
   TABLOCK
)

其中,假设authors.txt文件含有以下内容:

1,lauthor1, fauthor1,,address1,city1,CA,10002,1
2,lauthor2, fauthor2,,address2,city1,CA,10002,0
3,lauthor3, fauthor3,,address3,city1,CA,10002,1
4,lauthor4, fauthor4,,address4,city1,CA,10002,1
5,lauthor5, fauthor5,,address5,city1,CA,10002,1

......

2)bcp工具

bcp 实用工具在 Microsoft® SQL Server™ 2000 实例和数据文件之间以用户指定的格式复制数据。

2.1)从数据文件复制数据到指定的数据库表中

若要将数据从 Newpubs.dat 大容量复制到 publishers2,可以使用以下命令:

bcp pubs..publishers2 in newpubs.dat -c -t , -r /n -Sservername -Usa -Ppassword

其中Newpubs.dat 文件为:

1111,Stone Age Books,Boston,MA,USA
2222   ,Harley & Davidson,Washington,DC,USA
3333   ,Infodata Algosystems,Berkeley,CA,USA

2.2)从数据库复制数据到指定的文件

例如,Northwind 数据库内有表 Jane's Orders,该表由用户 Jane Doe 所拥有。若要使用登录 Jane Doe 和密码 go dba 将该表从 Northwind 数据库大容量复制到 Orders.txt 文件,请执行下列命令之一:

bcp "Northwind.Jane Doe.Jane's Orders" out "Jane's Orders.txt" -c -q -U"Jane Doe" -P"go dba"

bcp "Northwind.[Jane Doe].[Jane's Orders]" out "Jane's Orders.txt" -c -U"Jane Doe" -P"go dba"

 2.3)将数据从查询复制到数据文件


bcp 实用工具使您得以将 Transact-SQL 语句的结果集复制到数据文件中。该 Transact-SQL 语句可以是任何可返回结果集的有效语句,例如分布式查询或联接多个表的 SELECT 语句。例如

bcp "SELECT au_fname, au_lname FROM pubs..authors ORDER BY au_lname" queryout Authors.txt -c -Sservername -Usa -Ppassword

猜你喜欢

转载自blog.csdn.net/baodi_z/article/details/1815150