首先:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'xp_cmdshell', 1;
GO
RECONFIGURE;
GO

然后:

--导出表的情况

EXEC master..XP_cmdshell 'bcp 数据库名.dbo.表名 out "c:test.xls" /c -/S"服务器名" /U"用户名" -P"密码"'

--导出查询的情况

EXEC master..xp_cmdshell 'bcp "SELECT au_fname, au_lname FROM pubs..authors ORDER BY au_lname" queryout "c:test.xls" /c -/S"服务器名" /U"用户名" -P"密码"'

 

发生以下错误:
[Error][Microsoft][Native]Error = [Microsoft][SQL Native Client]无法打开 BCP 主数据文件

使用如下命令:
EXEC xp_cmdshell 'ECHO %USERDOMAIN%\%USERNAME%'
返回 :NT AUTHORITY\NETWORK SERVICE然后在配置管理器(configuration manager)里面的SQL server2005服务里打开,看到登陆内置账号为Network service,
改成local system问题解决。