sql怎么导出带标题的csv格式_SQLServer带列名导出到
Excel(Exportt。。。
前⼏天在项⽬中遇到⼀个问题,需要从SQL Server导出表到Excel,但需要带列名。晚上尝试了⼏种⽅法,并作个⼩结。
假定表如下:
USEtestDb2GO
IF NOT OBJECT_ID('Demo_A') IS NULL
DROP TABLE [Demo_A]
/****** Object: Table [dbo].[Demo_A] downmoon:3w@live ******/
CREATE TABLE [dbo].[Demo_A]([ID] int not null,[Name] [Nvarchar](20) NOT NULL)GO
INSERT [dbo].[Demo_A]
SELECT 1,'郭靖'
union ALL SELECT 2,'胡⼀⼑'
union ALL SELECT 3,'令狐冲'
GO
如果通常的思路,我们可以⽤BCP,命令如下:
--To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
--To update the currently configured value for advanced options.
RECONFIGURE
GO
--To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
--To update the currently configured value for this feature.
RECONFIGURE
GO
p_cmdshell 'bcp Testdb2.dbo.Demo_A out c:\Temp.xls -c -q -S"ap4\Net2012" -U"sa" -P"sA"'
⽅法⼀:使⽤BCP
为了⽅便,我创建了⼀个存储过程:
1 /****** SQL Export to xls ***************/
2 /*Example*/
3 /*CPP_Export_To_Excel_With_Header 'Testdb2','Demo_A','服务器名\实例名','C:\TestExxelWithHeader.xls'*/
4 /*2012.5.4 BY tony,邀⽉, 3w@live*/
5 ---- CPP_Export_To_Excel_With_Header 'Testdb2','Demo_A','localhost\SQLExpress','C:\TestExcelWithHeader.xls'
6
7 Create Procedure [dbo].[CPP_Export_To_Excel_With_Header]
8 (9 @db_name varchar(255),10 @table_name varchar(255),11 @server_name varchar(255),12 @file_path
varchar(255)13 )14 as
15
16 ----Generate column names as a recordset
17 declare @columns varchar(8000), @sql varchar(8000)18 declare @HeadersOnlyFile
varchar(255),@TableDataWithoutHeaders varchar(255)19 set @HeadersOnlyFile=replace(cast(newid() as VARCHAR(40)),'-','')+'1.xls'
20
21 set @TableDataWithoutHeaders=replace(cast(newid() as VARCHAR(40)),'-','')+'2.xls'
22 select
23 @columns=coalesce(@columns+',','')+column_name+'as'+column_name24 from
25 lumns26 where
27 table_name=@table_name
28 select @columns=''''''+replace(replace(@columns,'as','''''as'),',',',''''')29 print @columns
30 ----Generate column names file
31 set @sql='p_cmdshell''bcp " select * from (select'+@columns+') as t" queryout "'+@HeadersOnlyFile+'" -c -T -S'+@server_name+''''
32 print @sql
33 exec(@sql)34
35 ----Create a dummy file to have actual data
36 set @sql='p_cmdshell''bcp "'+@db_name+'..'+@table_name+'" out "'+@TableDataWithoutHeaders+'" -c -T -
S'+@server_name+''''
37 print @sql
38 exec(@sql)39
40 --Merge File into One Final Format
41 set @sql='p_cmdshell''copy /b'+@HeadersOnlyFile+'+'+@TableDataWithoutHeade
rs+' '+@file_path+''''
42 print @sql
43 exec(@sql)44
45 --Delete temp File
46 set @sql='p_cmdshell''del'+@HeadersOnlyFile+''''
47 exec(@sql)48 set @sql='p_cmdshell''del'+@TableDataWithoutHeaders+''''
49 exec(@sql)
调⽤⽅法:
exec CPP_Export_To_Excel_With_Header 'testdb2','Demo_A','myshop\SQLExpress','c:\Demo_A2.xls'
注意,报错的话:
isnull的用法1、SQL  Server是否以wndows登录⽅式或混合模式安装,参数中的“-c -T -S机器名\SQLExpress”,即机器名\实例,如果默认实例名与机器⼀致,⽤机器名即可。
2、也可以SA⽤户登录,请修改过程中的参数为BCP相应参数,见上⾯⽰例。
⽅法⼆:
1 ALTER procedure [dbo].[proc_generate_excel_with_header]
2 (
3 @db_name varchar(100),
4 @table_name varchar(100),
5 @server_name varchar(255),
6 @file_name varchar(100)
7 )
8 as
9
10 /****** SQL Export to xls ***************/
11 /*Example*/
12 /*proc_generate_excel_with_header 'Testdb','Demo_A','服务器名\实例名','c:\Demo_A.xls'*/
13 /*2020.1.2 BY tony,邀⽉, 3w@live*/
14 ---- proc_generate_excel_with_header 'Testdb','Demo_A','localhost\SQLExpress','C:\TestExcelWithHeader.xls'
15
16
17 --Generate column names as a recordset
18 DECLARE @raw_sql nvarchar(4000), @sql varchar(8000)19
20 DECLARE @columnHeader VARCHAR(8000)21 SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+
''''''+column_name +'''''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name
22
23 DECLARE @ColumnList VARCHAR(8000)24 SELECT @ColumnList = COALESCE(@ColumnList+',' ,'')+
'CAST('+column_name +'AS VARCHAR)' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name
25
26 SELECT @raw_sql = 'SELECT'+ @columnHeader +'UNION ALL SELECT' + @ColumnList + 'FROM' +
@db_name+'..'+@table_name
27 PRINT @raw_SQL
28 --EXECUTE sp_executesql @raw_sql
29
30 --filepath
31 ----select @file_name=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
32 if isnull(@server_name,'')=''
33 set @server_name='localhost'
34
35 --Generate data in the dummy file
36 set @sql='p_cmdshell''bcp "'+@raw_sql+'" queryout "'+@file_name+'" -c -T -S'+@server_name+''''
37 print @sql
38 exec(@sql)
调⽤⽰例:
exec proc_generate_excel_with_header 'testdb2','Demo_A','myshop\SQLExpress','c:\Demo_A.xls'
同样,报错的话:
1、SQL  Server是否以wndows登录⽅式或混合模式安装,参数中的“-c -T -S机器名\SQLExpress”,即机器名\实例,如果默认实例名与机器⼀致,⽤机器名即可。
2、也可以SA⽤户登录,请修改过程中的参数为BCP相应参数,见上⾯⽰例。
如果,你的环境是SQL Server 2005,那么可以有:
⽅法三,使⽤sp_makewebtask,仅适⽤于SQL Server 2005
0)表T1结构
aintbintxchar
1)开启Web Assistant Proceduresexec sp_configure 'show advanced options', 1
RECONFIGURE
exec sp_configure 'Web Assistant Procedures', 1
RECONFIGURE
2)执⾏如下语句EXECsp_makewebtask@outputfile = 'd:\testing.xls',@query = 'Select TOP 10 * from
shenliang1985..T1',@colheaders =1,@FixedFont=0,@lastupdated=0,@resultstitle='Querying details'
3)查看⽣成的EXCEl的
Querying details
Last updated:2010-03-03 01:02:59.263a b x0 0 0
2 5 1
4 10 2
6 15 3
8 20 4
10 25 5
12 30 6
14 35 7
16 40 8
18 45 9
可惜SQL Server 2008以后sp_makewebtask 这个存储过程取消了,后续版本也不再启⽤。
⽅法⼀和⽅法⼆其实⽣成的⽂件都不是真正的Excel⽂件,虽然后缀名为xls,为此,到邹建写的⼀个存储过程。
⽅法四,使⽤OpenRowSet:
/*--数据导出EXCEL
导出查询中的数据到Excel,包含字段名,⽂件为真正的Excel⽂件
如果⽂件不存在,将⾃动创建⽂件
如果表不存在,将⾃动创建表
基于通⽤性考虑,仅⽀持导出标准数据类型
--邹建 2003.10(引⽤请保留此信息)--*/
/*--调⽤⽰例
p_exporttb @sqlstr='select * from 地区资料'
,@path='c:\',@fname='aa.xls',@sheetname='地区资料'
--*/
create procp_exporttb@sqlstr varchar(8000),--查询语句,如果查询语句中使⽤了order by ,请加上top 100 percent
@path nvarchar(1000),--⽂件存放⽬录
@fname nvarchar(250),--⽂件名
@sheetname varchar(250)=''--要创建的⼯作表名,默认为⽂件名
as
declare @err int,@src nvarchar(255),@desc nvarchar(255),@out int
declare @obj int,@constr nvarchar(1000),@sql varchar(8000),@fdlist varchar(8000)--参数检测
if isnull(@fname,'')=''set @fname='temp2012.xls'
if isnull(@sheetname,'')='' set @sheetname=replace(@fname,'.','#')--检查⽂件是否已经存在
if right(@path,1)<>'\' set @path=@path+'\'
create table #tb(a bit,b bit,c bit)set @sql=@path+@fname
insert into #tb p_fileexist @sql
--数据库创建语句
set @sql=@path+@fname
if exists(select 1 from #tb where a=1)set @constr='DRIVER={Microsoft Excel Driver (*.xls)};DSN='''';READONLY=FALSE' +';CREATE_DB="'+@sql+'";DBQ='+@sql
else
set @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES'
+';DATABASE='+@sql+'"'
--连接数据库
exec @err=sp_oacreate 'tion',@objoutif @err<>0 gotolberrexec @err=sp_oamethod @obj,'open',null,@constr if @err<>0 gotolberr--创建表的SQL
declare @tbnamesysnameset @tbname='##tmp_'+convert(varchar(38),newid())set @sql='select * into ['+@tbname+']
from('+@sqlstr+') a'

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。