在sqlserver中使用bcp自动导出数据的方法和注意事项

今天测试了下sqlserver中BCP导出数据的功能,可以在sqlserver studio中的查询窗口中使用,也可以在命令行中使用。

方法1:在查询窗口中使用。在查询窗口中使用必需通过sp_configure打开xp_cmdshell的运行许可

sp_configure设置打开xp_cmdshell的脚本
 1 -- To allow advanced options to be changed.
 2 EXEC sp_configure 'show advanced options'1
 3 GO
 4 -- To update the currently configured value for advanced options.
 5 RECONFIGURE
 6 GO
 7 -- To enable the feature.
 8 EXEC sp_configure 'xp_cmdshell'1
 9 GO
10 -- To update the currently configured value for this feature.
11 RECONFIGURE
12 GO

 

 在打开xp_cmdshell的运行许可后,可以运行如下(设表库为test,表为 ryxx)

在查询窗口中导出数据,使用“用户名及密码的方式”
1 EXEC master..xp_cmdshell 'bcp test.dbo.ryxx out c:\currency1.txt -c -U"用户名" -P"密码"'
 

 

以可信连接方式
1 EXEC master..xp_cmdshell 'bcp test.dbo.ryxx out c:\currency1.txt -c -T'

 注意:在查询窗口中执行时可能会出现如下的错误(如下图1所示),这是因为没有对目录添加读写权限造成的,我将输出目录改为“d:\temp”,并添加了NETWORK SERVICE的读写权限(如图2所示),问题解决

bcp在查询窗口执行的错误
图1

给目录添加读写权限
图2

方法2:在命令行中导出,首先bcp的执行程序位于 “C:\Program Files\Microsoft SQL Server\100\Tools\Binn\"

以可信连接方式
bcp test.dbo.ryxx out c:\currency1.txt --T

  

以用户名密码方式
1 bcp test.dbo.ryxx out c:\currency1.txt --U"用户名" -P"密码"

 

 注意,表名最好是没有特殊字符和“-”的字符串,我的表名为2012-06-25时提示出错。

 

posted @ 2012-06-25 18:05  GDLMO  阅读(1335)  评论(0编辑  收藏  举报