Send the query results in a tabular form using DBmail and SQL server agent.

declare @emailSubject varchar(100),

@columnHeaders varchar(1000),

@tableHTML nvarchar(max)

select @emailSubject = ‘report’,             — Subject of Email

@columnHeaders = ‘session_id </th><th> DB_Name </th><th> host_name </th><th> program_name </th><th> client_interface_name </th><th> login_name </th><th> nt_domain </th><th> nt_user_name </th><th>

connect_time </th><th> login_time</th><th>’    — Column headers (must put </th><th> between each header)

if (select COUNT(*) from sys.dm_exec_connections AS c

JOIN sys.dm_exec_sessions AS s  ON c.session_id = s.session_id

WHERE c.session_id in (select session_id from sys.dm_exec_requests where database_id not  in (‘1′,’4’) )) >0

begin

set @tableHTML =

‘<div><b>user report</b></div><br>’ + — This is the bold text at the top of your email.

‘<table border=”1″ cellpadding=”5″><font face=”Calibri” size=2>’ +

‘<tr><th>’ + @columnHeaders + ‘</th></tr>’ +

convert(nvarchar(max),

(

SELECT

td = c.session_id,”,

td = DB_NAME(database_id),”,

td = s.host_name,”,

td = s.program_name,”,

td =  s.client_interface_name,”,

td = s.login_name,”,

td = s.nt_domain,”,

td =  s.nt_user_name,”,

td =  c.connect_time,”,

td = s.login_time,”

FROM sys.dm_exec_connections AS c

JOIN sys.dm_exec_sessions AS s  ON c.session_id = s.session_id

WHERE c.session_id in (select session_id from sys.dm_exec_requests where database_id not  in (‘1′,’4’) ) )

for xml path(‘tr’), type

)) +

–‘</font>’

‘</table>’

exec msdb.dbo.sp_send_dbmail

@recipients = ‘@mail.com;’,              — Email address of recipient

@body = @tableHTML,

@subject = @emailSubject,

@body_format = ‘HTML’

end

else

begin

exec msdb.dbo.sp_send_dbmail

@recipients = ‘@mail.com;’,              — Email address of recipient

@body = ‘0 rows effected’,

@subject = @emailSubject,

@body_format = ‘HTML’

END

Get failed jobs report — SQL Server

——–Script to get the failed jobs report

BEGIN
SET NOCOUNT ON
SELECT Convert(varchar(20),SERVERPROPERTY(‘ServerName’)) AS ServerName,
j.name AS job_name,
CASE jh.run_status WHEN 0 THEN ‘Failed’
WHEN 1 THEN ‘Succeeded’
WHEN 2 THEN ‘Retry’
WHEN 3 THEN ‘Canceled’
WHEN 4 THEN ‘In Progress’ ELSE
‘Status Unknown’ END AS ‘last_run_status’,jh.message as MessageDetails
FROM
(msdb.dbo.sysjobactivity ja LEFT JOIN msdb.dbo.sysjobhistory jh ON
ja.job_history_id = jh.instance_id)
join msdb.dbo.sysjobs_view j on ja.job_id = j.job_id
WHERE ja.session_id=(SELECT MAX(session_id) from msdb.dbo.sysjobactivity)
and jh.run_status = 0 ORDER BY job_name
END