2012年11月9日 星期五

SQL2000將select後的資料匯成EXCEL

把select後的結果,匯出成一個EXCEL並存檔‧
參考:http://weblogs.sqlteam.com/mladenp/archive/2006/07/25/10771.aspx
先建一個預存程式


create proc spExportData 
(
    @dbName varchar(100) = 'master', 
    @sql varchar(5000) = '',     
    @fullFileName varchar(100) = ''
)
as
if @sql = '' or @fullFileName = ''
begin
    select 0 as ReturnValue -- failure
    return
end 
-- if DB isn't passed in set it to master
select    @dbName = 'use ' + @dbName + ';'
if object_id('##TempExportData') is not null
    drop table ##TempExportData
if object_id('##TempExportData2') is not null
    drop table ##TempExportData2
-- insert data into a global temp table
declare @columnNames varchar(8000), @columnConvert varchar(8000), @tempSQL varchar(8000)
select    @tempSQL = left(@sql, charindex('from', @sql)-1) + ' into ##TempExportData ' + 

     substring(@sql, charindex('from', @sql)-1, len(@sql))
exec(@dbName + @tempSQL)
if @@error > 0
begin
    select 0 as ReturnValue -- failure
    return
end 
-- build 2 lists
-- 1. column names
-- 2. columns converted to nvarchar
SELECT    @columnNames = COALESCE( @columnNames  + ',', '') + column_name,
        @columnConvert = COALESCE( @columnConvert  + ',', '') + 'convert(nvarchar(4000),' 
        + column_name + case when data_type in ('datetime', 'smalldatetime') then ',121'
                             when data_type in ('numeric', 'decimal') then ',128'
                             when data_type in ('float', 'real', 'money', 'smallmoney') then ',2'
                             when data_type in ('datetime', 'smalldatetime') then ',120'
                             else ''
                        end + ') as ' + column_name
FROM    tempdb.INFORMATION_SCHEMA.Columns
WHERE    table_name = '##TempExportData'
-- execute select query to insert data and column names into new temp table
SELECT    @sql = 'select ' + @columnNames + ' into ##TempExportData2 from (select ' + @columnConvert + ', ''2'' as [temp##SortID] 
       from ##TempExportData union all select ''' + replace(@columnNames, ',', ''', ''') + ''', ''1'') t order by [temp##SortID]'
exec (@sql)
-- build full BCP query
select    @sql = 'bcp "' + @dbName + ' select * from ##TempExportData2" queryout "' + @fullFileName + '" -c -CRAW'
-- execute BCP
Exec master..xp_cmdshell @sql
if @@error > 0
begin 
    select 0 as ReturnValue -- failure
    return
end
drop table ##TempExportData
drop table ##TempExportData2
select 1 as ReturnValue -- success
GO
轉換EXCEL範例:

declare @sql varchar(6800),    @dbName varchar(100), @fullFileName varchar(100)
select    @dbName = 'northwind', @sql = 'select * from orders order by orderdate', @fullFileName = 'e:\test.xls'
exec    master..spExportData @dbName, @sql, @fullFileName 

這方法是利用MSSQL的工具程式:bcp.exe來寫資料出去,但它設計是在作業系統層或外部程式呼叫的(例如:command line)而不能從T-SQL中呼叫。連結中的作法是先利用Exec master..xp_cmdshell讓T-SQL可以進到作業系統的Command Line模式接下來就是當成外部程式來呼叫它

0 意見: