bulk insert语句和bcp实用工具
http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/
bulk insert语句和bcp实用工具用于在SQL SERVER 数据库和数据文件之间复制数据.
(ps:关于导入和导出数据的更多使用方法,可以参考《sql server联机丛书》的 “管理 SQL Server ”-->“导入和导出数据”章节)
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
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,USA2222 ,Harley & Davidson,Washington,DC,USA3333 ,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"
-Turn on Advanced features
EXEC sp_configure 'show advanced options', 1
reconfigure
go
--Turn on xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
reconfigure
go
--Run script
exec master.dbo.xp_cmdshell '"C:/Program Files/....type path ''"C:/Program Files/VERITAS/NetBackup/DbExt/MsSql/typename"'' -p Test_Sql -u username -pw password -np', no_output
go
--Turn off xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 0
reconfigure
go
--Turn off advanced options
EXEC sp_configure 'show advanced options', 0
reconfigure
go
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