使用BCP和commandShell将数据导出到excel

时间:2017-08-16 11:15:45

标签: sql-server sql-server-2008 export-to-excel bcp xp-cmdshell

我正在从视图中选择数据

我收到错误

usage: bcp [[db_name.]owner.]table_name[:slice_num] [partition pname] {in | out} [filename]
[-m maxerrors] [-f formatfile] [-e errfile] [-d discardfileprefix] 
[-F firstrow] [-L lastrow] [-b batchsize]
[-n] [-c] [-t field_terminator] [-r row_terminator]
[-U username] [-P password] [-I interfaces_file] [-S server]
[-a display_charset] [-z language] [-v]
[-i input_file] [-o output_file] 
[-A packet size] [-J client character set] 
[-T text or image size] [-E] [-g id_start_value] [-N] [-W] [-X]
[-M LabelName LabelValue] [-labeled]
[-K keytab_file] [-R remote_server_principal] [-C]
[-V [security_options]] [-Z security_mechanism] [-Q] [-Y]
[-y sybase directory] [-x trusted.txt_file]
[--clienterr errfile] [--maxconn maximum_connections]
[--show-fi] [--hide-vcc]
[--colpasswd [[[db_name.[owner].]table_name.]column_name [password]]]
[--keypasswd [[db_name.[owner].]key_name [password]]]
[--initstring ASE initialization string] [--quoted-fname]

NULL

declare @sql varchar(8000)

Select @sql=  'bcp "Select * from eBenefitSync_GUI_PH.dbo.Disp_View" out D:\Contacts.txt -c -T ' +'-s ' +@@servername+'\'+@@servicename
--EXECUTE master.dbo.xp_cmdshell @SQL

2 个答案:

答案 0 :(得分:0)

该用法告诉您它需要database.table语法,而不是SQL查询。尝试删除select * from:

declare @sql varchar(8000)

Select @sql=  'bcp "eBenefitSync_GUI_PH.dbo.Disp_View" out D:\Contacts.txt -c -T ' +'-s ' +@@servername+'\'+@@servicename
--EXECUTE master.dbo.xp_cmdshell @SQL

答案 1 :(得分:0)

要使用BCP导出查询,您需要使用queryout parameter而不是out参数。 out parameter只能直接查询表或视图,而不能查询。