将SQL查询结果导出到Excel

时间:2014-01-14 14:25:32

标签: sql-server export

执行下述声明时:

EXEC proc_generate_excel_with_columns 
     'your dbname', 'your table name','your file path'

我收到以下错误。有人可以帮忙吗?

  

未提供用户名,使用-U提供用户名或使用   -T for Trusted Connection用法:bcp {dbtable |查询} {in |出| queryout |格式} datafile [-m maxerrors] [-f formatfile] [-e   errfile] [-F firstrow] [-L lastrow] [-b batchsize] [-n native type]   [-c字符类型] [-w宽字符类型] [-N保持非文本字符]   [-V file format version] [-q quoted identifier] [-C code page   说明符] [-t字段终止符] [-r行终止符] [-i inputfile]   [-o outfile] [-a packetsize] [-S服务器名称] [-U用户名] [-P   密码] [-T可信连接] [-v版本] [-R区域启用]   [-k keep null values] [-E keep identity values] [-h“load hints”] [-x   生成xml格式文件] [-d数据库名称] NULL

我的程序是:

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 

from 
    information_schema.columns
where 
    table_name='dbo.vcuriosoftronic.tblPayrollGroups'
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring('D:\TestFile.xls',1,len('D:\TestFile.xls')
                            -charindex('\',reverse('D:\TestFile.xls')))
                            +'D:\TestFile.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp
          " select * from (select '+@columns+') as t"
          queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp
         "select * from [myserver]..'+@table_name+'"
         queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

1 个答案:

答案 0 :(得分:1)

查看我的博客文章,了解如何使用BCP导出数据。

http://craftydba.com/?p=1690

以下代码段使用-T,可信连接。如果您在代理下运行作业,它将在该安全帐户下运行。

请传递标准安全凭证-U -P或确保该帐户能够运行该命令。

-- BCP - Export query, pipe delimited format, trusted security, character format
DECLARE @bcp_cmd4 VARCHAR(1000);
DECLARE @exe_path4 VARCHAR(200) = 
    ' cd C:\Program Files\Microsoft SQL Server\100\Tools\Binn\ & ';
SET @bcp_cmd4 =  @exe_path4 + 
    ' BCP.EXE "SELECT FirstName, LastName FROM AdventureWorks2008R2.Sales.vSalesPerson" queryout ' +
    ' "C:\TEST\PEOPLE.TXT" -T -c -q -t0x7c -r\n';
PRINT @bcp_cmd4;
EXEC master..xp_cmdshell @bcp_cmd4;
GO

假设BCP路径位于搜索列表中,则更新。下面是删除了路径并为SQL Server 2012更改了查询的屏幕截图。

enter image description here

查看消息窗口,它具有print语句中的BCP命令。您可以将命令放入批处理文件以从DOS提示符进行测试。这是一个调试练习。