複製數據--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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章