SQL Server Procedure to Export Query result to Excel

I recently created these SQL Server 64 bit Procedure to help export query result to existing excel

enjoy


USE [devdb]
GO
/****** Object: StoredProcedure [dbo].[exportquery2excel] Script Date: 11/14/2014 4:01:12 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Indradhi Nugraha Mulyanto
-- Create date: 15/11/2014 16:02
-- Description: Export Query to Excel
-- Parameters:
-- @query : database query ex. 'SELECT [Name], GETDATE() FROM msdb.dbo.sysjobs'
-- @existingexcelfile : existing excel directory and filename ex. 'E:\SUPM\testing.xlsx'
-- @sheet : excel sheet targeted ex. 'Sheet1'
-- @headerrow : header row where data will be exported after header row ex. 1
-- @firstcolumn : first column of excel data will be exported ex. a
-- @lastcolumn : last column of excel data will be exported, must be greater than @firstcolumn ex. g
-- =============================================
ALTER PROCEDURE [dbo].[exportquery2excel]
-- Add the parameters for the stored procedure here
@query varchar(max),
@existingexcelfile varchar(max),
@sheet varchar(max),
@headerrow integer,
@firstcolumn varchar(10),
@lastcolumn varchar(10)

AS
BEGIN

DECLARE @sql varchar(max);

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

BEGIN TRY
-----------------------------------------------------------------

SET @sql = ('INSERT INTO OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',''Excel 8.0;Database='+@existingexcelfile+';'',''SELECT * FROM ['+@sheet+'$'+@firstcolumn+cast(@headerrow as varchar)+':'+@lastcolumn+']'') '+ @query);
--print(@sql);
execute(@sql);
-----------------------------------------------------------------
END TRY

BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;

IF @@TRANCOUNT > 0
begin
ROLLBACK TRANSACTION;
end
END CATCH;

IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
END

Published by indradhi

coding + sharing = influence

Leave a comment