DB Mail with CSV Attachment to Users by using BCP command
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[EmailReport]
@ReportName AS VARCHAR(10)
, @Country AS VARCHAR(4000)
, @Date AS DATE
, @FromDate AS DATE
, @ToDate AS DATE
, @Schedule AS VARCHAR(4000)
, @Mailrecipients as varchar(4000)
AS
BEGIN
DECLARE @Datestring varchar(100)
SET @Datestring = CONVERT(VARCHAR(10), @Date, 101)
PRINT @Datestring
DECLARE @FileName AS VARCHAR(4000)
DECLARE @string AS VARCHAR(4000)
DECLARE @Columns AS VARCHAR(4000)
DECLARE @MailSubject AS VARCHAR(4000)
DECLARE @MailBody AS VARCHAR(4000)
SET @MailBody = 'Attached is the ' + @Schedule + ' Report. Please do not Reply back as this is a System Generated Email.'
IF (@ReportName = 'Employee Details')
BEGIN
-- Generate the Report
SET @FileName = 'E:\Employee\SQLJob\EmployeeRecord'+Replace (@Country,' ','')+ CONVERT(VARCHAR(10), @Date, 112)+ '.CSV'
-- Command Shell for Report Generation Create a Query for retriving Records in the Below Procedure --
SELECT @string = 'bcp "EXEC [Employee].[dbo].[EmployeeRecord] @Date = '''+ @Datestring +''', @Country = '''+@Country+'''" queryout '+@FileName+' -t, -c -S. -T'
exec master.dbo.xp_cmdshell @string
-- Mail Subject
SET @MailSubject = @Schedule + ' Employee Report for '+ @Country +' as on ' + @Datestring
END
ELSE
BEGIN
SET @Datestring = CONVERT(VARCHAR(10), @ToDate, 101)
-- Generate the Report
SET @FileName = 'E:\Employee\SQLJob\ExitReport'+Replace (@Country,' ','') +CONVERT(VARCHAR(10), GETDATE(), 112)+ '.CSV'
-- Command Shell for Report Generation
SELECT @string = 'bcp "EXEC [Employee].[dbo].[EmployeeExitReport] @ToDate = '''+ @Datestring +''', @FromDate = '''+ CONVERT(VARCHAR(10), @FromDate, 101) +''', @Country = N'''+@Country+'''" queryout '+@FileName+' -t, -c -S. -T'
exec master.dbo.xp_cmdshell @string
-- Mail Subject
SET @MailSubject = @Schedule + ' Exit Report For -'+ @Country +' as on ' + @Datestring
END
-- Email the Generated Report
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Employee'
, @recipients = @Mailrecipients
, @body = @MailBody
, @file_attachments = @FileName
, @body_format = 'HTML'
, @subject = @MailSubject;
END
Comments
Post a Comment