Automate SQL query to send excel spreadsheet via email

Steel Contributor

I have this SQL query that runs perfect. I now would like to automate it as a stored procedure that emails the results in an Excel spreadsheet. Any pointer? Thanks for any help you can provide.

 

Here is the query:

select SiteID,
case 
	when SiteID = '001' then 'Omaha Terminal'
	else 'Geneva Terminal'
	end as 'Site Name'
	  ,rtrim([TransNum])+replicate(' ',5-len(TransNum)) [Transaction Num]
	  ,rtrim([Date])+replicate(' ',20-len(Date)) [Transaction Date]
	  ,rtrim([Time])+replicate(' ',20-len(Time)) [Time]
	  ,rtrim([Card1])+replicate(' ',20-len(Card1)) [Card]
	  ,rtrim(c.[Name])+replicate(' ',20-len(c.Name)) [Name]
	  ,rtrim(t.[UserEntry2])+replicate(' ',10-len(t.UserEntry2)) [Tractor]
	  ,rtrim(t.[UserEntry3])+replicate(' ',10-len(t.UserEntry3)) [Odometer]
	  ,rtrim([Qty])+replicate(' ',5-len(Qty)) [Quantity]
from Transactions t
left join Card c
on t.Card1 = c.CardNumber
where t.Date  between '07-19-2021' and '07-20-2021'
order by [Transaction Date] desc
1 Reply

https://www.sqlservercentral.com/scripts/create-excel-xls-from-t-sql

It creates excel file, you can send it as attachment.

The script is very old,  you will need replace in this script "Microsoft.Jet.OLEDB.4.0" to "Microsoft.ACE.OLEDB.12.0"
and install "Microsoft Access Database Engine 2010 Redistributable " x32 or x64 - depending what version of Office you have installed.