sql bcp Utility工具使用

bcp全称是Command Prompt Utilities,主要用来在数据库和数据文件中导入导出数据。

用法如下:

usage: bcp {dbtable | query} {in | out | queryout | format} datafile
  [-m maxerrors]            [-f formatfile]          [-e errfile]
  [-F firstrow]             [-L lastrow]             [-b batchsize]
  [-n native type]          [-c character type]      [-w wide character type]
  [-N keep non-text native] [-V file format version] [-q quoted identifier]
  [-C code page specifier]  [-t field terminator]    [-r row terminator]
  [-i inputfile]            [-o outfile]             [-a packetsize]
  [-S server name]          [-U username]            [-P password]
  [-T trusted connection]   [-v version]             [-R regional enable]
  [-k keep null values]     [-E keep identity values]
  [-h "load hints"]         [-x generate xml format file]

现在我们从数据文件中导入数据到数据表中,我们需要一个格式文式,来定义从文本到数据库中字段的转化。

请注意,bcp里的参数设定是区别大小写的。

举例说明:bcp database.dbo.dataTable format nul –f C:\dataTable.fmt -x –c –T –S sql

database指定进行操作的数据

dbo指定数据库的所有者

dataTable指定数据库中的某个表

format nul –f C:\dataTable.fmt –x –c  指定导出的格式文件的存储位置和名称,-x说明的生xml格式的格式文件(推荐使用),-c指使用tab和换行来区分各个字段

-T 说明使用安全连接,采用windows认证,如果无法通过windows认证,可以使用sql认证,-U [username] –P [password]

-S 如果数据库不在本机,要指定你要连接的数据库服务器的名字

下面我们把数据表中的数据导出到数据文件中(数据库中的数据并不删除)。

举例说明:bcp database.dbo.dataTable out C:\output.txt –T –c –S sql

-S指明数据库服务器,database.dbo.dataTable指明数据库及表,-T使用windows认证

out C:\output.txt 指明这次操作做的是导出操作,把数据导出到C:\output.txt文件中

-c 产生以tab(\t)分隔列,换行(\r\n)分隔行的数据文件

现在我们可以再把数据文件按照格式文件的格式导入数据库中

举例说明:bcp database.dbo.dataTable in C:\output.txt –f C:\dataTable.fmt –e C:\error.txt –T –m 10 –S sql

in C:\output.txt指定这次操作是导入操作,且从output.txt文件导入

-e C:\error.txt如果在导入过程中发生错误,会将错误日志保存到这个文件中

-m 10指定允许发生错误的次数,当发生错误次数超出设定(在这里是10),这次导入操作次失败,回滚操作

参考资料:bcp UtilityCreating a Format File

posted on 2009-02-08 19:12  hzwang  阅读(936)  评论(0编辑  收藏  举报

导航