--创立SQLDMO.SQLServer工具
EXEC@hr=sp_OACreateSQLDMO.SQLServer,@SQLServerOUT
IF@hr0
BEGIN
PRINTerrorcreateSQLDMO.SQLServer
RETURN
END
--毗连到SQLServer体系
IF@pwdISNULL
BEGIN
EXEC@hr=sp_OAMethod@SQLServer,Connect,null,@server,@uname
IF@hr0
BEGIN
PRINTerrorConnect
RETURN
END
END
ELSE
BEGIN
EXEC@hr=sp_OAMethod@SQLServer,Connect,null,@server,@uname,@pwd
IF@hr0
BEGIN
PRINTerrorConnect
RETURN
END
END
--TheExecuteWithResultsmethodexecutesaTransact-SQLcommandbatch
--returningbatchresultsetsinaQueryResultsobject
SELECT@result_str=ExecuteWithResults("+@QueryText+")
EXEC@hr=sp_OAMethod@SQLServer,@result_str,@QueryResultsOUT
IF@hr0
BEGIN
PRINTerrorwithmethodExecuteWithResults
RETURN
END
--TheCurrentResultSetpropertycontrolsaccesstotheresultsetsofaQueryResultsobject
EXEC@hr=sp_OAMethod@QueryResults,CurrentResultSet,@CurrentResultSetOUT
IF@hr0
BEGIN
PRINTerrorgetCurrentResultSet
RETURN
END
--TheColumnspropertyexposesthenumberofcolumnscontained
--inthecurrentresultsetofaQueryResultsobject
EXEC@hr=sp_OAMethod@QueryResults,Columns,@ColumnsOUT
IF@hr0
BEGIN
PRINTerrorgetColumns
RETURN
END
--TheRowspropertyreturnsthenumberofrowsinareferenced
--queryresultsetorthenumberofrowsexistinginatable
EXEC@hr=sp_OAMethod@QueryResults,Rows,@RowsOUT
IF@hr0
BEGIN
PRINTerrorgetRows
RETURN
END
--创立Excel.Application工具
EXEC@hr=sp_OACreateExcel.Application,@objectOUT
IF@hr0
BEGIN
PRINTerrorcreateExcel.Application
RETURN
END
--取得Excel事情簿工具
EXEC@hr=sp_OAGetProperty@object,WorkBooks,@WorkBooksOUT
IF@hr0
BEGIN
PRINTerrorcreateWorkBooks
RETURN
END
--在事情簿工具中到场一事情表
EXEC@hr=sp_OAGetProperty@WorkBooks,Add,@WorkBookOUT
IF@hr0
BEGIN
PRINTerrorwithmethodAdd
RETURN
END
--Range工具(A1单位格)
EXEC@hr=sp_OAGetProperty@object,Range("A1"),@RangeOUT
IF@hr0
BEGIN
PRINTerrorcreateRange
RETURN
END
WHILE(@indRow<=@Rows)
BEGIN
SELECT@indColumn=1
WHILE(@indColumn<=@Columns)
BEGIN
--TheGetColumnStringmethodreturnsaQueryResultsobjectresultsetmemberconvertedtoaStringvalue
EXEC@hr=sp_OAMethod@QueryResults,GetColumnString,@result_strOUT,@indRow,@indColumn
IF@hr0
BEGIN
PRINTerrorgetGetColumnString
RETURN
END
EXEC@hr=sp_OASetProperty@Range,value,@result_str
IF@hr0
BEGIN
PRINTerrorsetvalue
RETURN
END
EXEC@hr=sp_OAGetProperty@Range,Offset,@RangeOUT,@off_Row,@off_Column
IF@hr0
BEGIN
PRINTerrorgetOffset
RETURN
END
SELECT@indColumn=@indColumn+1
END
SELECT@indRow=@indRow+1
SELECT@code_str=Range("A+LTRIM(str(@indRow))+")
EXEC@hr=sp_OAGetProperty@object,@code_str,@RangeOUT
IF@hr0
BEGIN
PRINTerrorcreateRange
RETURN
END
END
SELECT@result_str=execmaster..xp_cmdshelldel+@filename+,no_output
EXEC(@result_str)--假如存在@filename文件,则先删除
SELECT@result_str=SaveAs("+@filename+")
EXEC@hr=sp_OAMethod@WorkBook,@result_str
IF@hr0
BEGIN
PRINTerrorwithmethodSaveAs
RETURN
END
EXEC@hr=sp_OAMethod@WorkBook,Close
IF@hr0
BEGIN
PRINTerrorwithmethodClose
RETURN
END
EXEC@hr=sp_OADestroy@object
IF@hr0
BEGIN
PRINTerrordestroyExcel.Application
RETURN
END
EXEC@hr=sp_OADestroy@SQLServer
IF@hr0
BEGIN
PRINTerrordestroySQLDMO.SQLServer
RETURN
END
GO