资源描述:
《sql2008到如到excel》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、SQLServer2008中SQL应用系列及BI学习笔记系列--目录索引今天在项目中遇到一个问题,需要从SQLServer导出表到Excel,但需要带列名。尝试了几种方法,并小结如下:假定表如下:USEtestDb2GOIFNOTOBJECT_ID('Demo_A')ISNULLDROPTABLE[Demo_A]/Object:Table[dbo].[Demo_A]downmoon:3w@live.cn/CREATETABLE[dbo].[Demo_A]([ID]intnotnull,[Name][Nvarchar](20)NOTNULL)GOINSERT[dbo].[Demo_
2、A]SELECT1,'郭靖'unionALLSELECT2,'胡一刀'unionALLSELECT3,'令狐冲'GO如果通常的思路,我们可以用BCP,命令如下:--Toallowadvancedoptionstobechanged.EXECsp_configure'showadvancedoptions',1GO--Toupdatethecurrentlyconfiguredvalueforadvancedoptions.RECONFIGUREGO--Toenablethefeature.EXECsp_configure'xp_cmdshell',1GO--Toupdatethe
3、currentlyconfiguredvalueforthisfeature.RECONFIGUREGOEXECmaster..xp_cmdshell'bcpTestdb2.dbo.Demo_Aoutc:Temp.xls-c-q-S"ap4Net2012"-U"sa"-P"sA"'这样得到的xls文件中,Sheet是不带列名的。但可以改进一下,得到如下命令(参考:http://social.msdn.microsoft.com/forums/en-US/sqlgetstarted/thread/812b8eec-5b77-42a2-bd23-965558ece5b9/):方法
4、一:使用BCP为了方便,我创建了一个存储过程:/SQLExporttoxls//Example//CPP_Export_To_Excel_With_Header'Testdb2','Demo_A','C:TestExxelWithHeader.xls'//2012.5.4BYtony,邀月,3w@live.cn/----CPP_Export_To_Excel_With_Header'Testdb2','Demo_A','C:TestExcelWithHeader.xls'CreateProcedureCPP_Export_To_Excel_With_Header(@db_na
5、mevarchar(255),@table_namevarchar(255),@file_pathvarchar(255))as----Generatecolumnnamesasarecordsetdeclare@columnsvarchar(8000),@sqlvarchar(8000)declare@HeadersOnlyFilevarchar(255),@TableDataWithoutHeadersvarchar(255)set@HeadersOnlyFile=replace(cast(newid()asVARCHAR(40)),'-','')+'1.xls'set@Ta
6、bleDataWithoutHeaders=replace(cast(newid()asVARCHAR(40)),'-','')+'2.xls'select@columns=coalesce(@columns+',','')+column_name+'as'+column_namefrominformation_schema.columnswheretable_name=@table_nameselect@columns=''''''+replace(replace(@columns,'as','''''as'),',',',''''')print@columns----Gene
7、ratecolumnnamesfileset@sql='execmaster..xp_cmdshell''bcp"selectfrom(select'+@columns+')ast"queryout"'+@HeadersOnlyFile+'"-c'''print@sqlexec(@sql)----Createadummyfiletohaveactualdataset@sql='execmaster..xp_cmdshell''bcp"'+@db_name+'.dbo.'+@tab