Recently, I was asked if I can write and run a specific query and have the results, (if any) emailed to a specific group of people every day? But only send the email if the query returns results. Who wants to open and empty email after all?

最近,有人问我是否可以编写和运行特定查询,并每天将结果(如果有)通过电子邮件发送给特定人群? 但是仅在查询返回结果时才发送电子邮件。 谁最终想打开和清空电子邮件?

As with any DBA, we need a way to automate this process, as our time is valuable. Who wants to manually run a script, paste it into excel and then email it directly to users every morning?

与任何DBA一样,我们需要一种自动执行此过程的方法,因为我们的时间很宝贵。 谁想手动运行脚本,将其粘贴到excel中,然后每天早晨直接通过电子邮件发送给用户?

First things first, setup Database Mail if you haven’t already. (If you have already, feel free to skip this section).

首先,请设置数据库邮件(如果尚未安装)。 (如果已经拥有,请随时跳过本节)。

The best way to do this is to use the Database Mail Configuration Wizard.

最好的方法是使用数据库邮件配置向导。

Open SSMS, Expand Management and Right-click Database Mail -> Then click “Configure Database Mail”

打开SSMS,展开管理,然后右键单击数据库邮件->然后单击“配置数据库邮件”

Set up Database Mail:

设置数据库邮件:

Give the profile a name and then add an SMTP account.

为配置文件命名,然后添加一个SMTP帐户。

You can use whatever you’d like to for the account name, but you will have to get the server name and SMTP Authentication information from your systems or mail administrator.

您可以使用任意名称作​​为帐户名称,但是必须从系统或邮件管理员那里获取服务器名称和SMTP身份验证信息。

Select the right profile and press next and finish in the screens that follow:

选择正确的配置文件,然后按下一步,然后在随后的屏幕中完成:

(Feel free to reference for more detailed information on how to setup database mail).

(有关如何设置数据库邮件的更多详细信息,请随时参考 )。

Remember the profile name, because we’re going to use it when writing our little script.

记住配置文件名称,因为我们将在编写我们的小脚本时使用它。

So, just for the sake of this blog article, let’s come up with a simple script.

因此,仅出于这篇博客文章的目的,让我们提出一个简单的脚本。

Let’s pretend we need a list of employees from the employee table whose current employment status is false, or 0 (if using a bit column date type).

假设我们需要一个来自employee表的雇员列表,该雇员列表的当前雇用状态为false或0(如果使用位列日期类型)。


SELECT Name, EmploymentStatus, StartDate FROM dbo.Employee
WHERE EmploymentStatus = 0

Great, now we need to utilize the mail profile we setup to send this list to the appropriate recipients or distribution list. (Note, in an effort to make our code as clean as possible, it’s highly recommended that you have your mail administrator create a distribution list and add every one of the recipients. Not only does this make the code clean, it will be easy to add new email addresses to the list so that they can receive the reports).

太好了,现在我们需要利用我们设置的邮件配置文件将此列表发送到适当的收件人或通讯组列表。 (请注意,为了尽量使我们的代码更简洁,强烈建议您让邮件管理员创建一个通讯组列表并添加每个收件人。这不仅使代码更简洁,而且很容易在列表中添加新的电子邮件地址,以便他们可以接收报告)。

Now we use the stored procedure (msdb.dbo.sp_send_dbmail) and provide the values for the following parameters. (To get more detailed information regarding this stored procedure feel free to explore this link).

现在,我们使用存储过程(msdb.dbo.sp_send_dbmail)并提供以下参数的值。 (要获取有关此存储过程的更多详细信息,请随时浏览此链接 )。


beginexec msdb.dbo.sp_send_dbmail
@profile_name = 'QA_Notification’,
@recipients = ‘human_resources@company.com’
@subject = ‘Employment Status’,
@query = ' SELECT Name, EmploymentStatus, StartDate FROM dbo.Employee
WHERE EmploymentStatus = 0’,
@attach_query_result_as_file = 1,
@query_attachment_filename = 'EmploymentStatus.csv'End

You can test out the code within a query window, but our goal is to have it send it automatically. Thus we can create a SQL Agent Job and schedule it to run every morning (or as per the request of the users).

您可以在查询窗口中测试代码,但我们的目标是使它自动发送。 因此,我们可以创建一个SQL Agent Job并将其安排为每天早晨运行(或根据用户要求运行)。

But what if there are zero records to report? Do you really think the recipients want to go through the hassle of getting an email if there are zero results to the query? Well we can add one additional piece of code to remedy this. And it’s really quite simple!

但是,如果要报告的记录为零,该怎么办? 如果查询结果为零,您是否真的认为收件人希望解决发送电子邮件的麻烦? 好吧,我们可以添加一小段代码来解决这个问题。 这真的很简单!


IF (SELECT COUNT(*) FROM dbo.Employe WHERE EmploymentStatus = 0)> 0

Add this piece of code to the top to verify that there are rows to return. If it’s greater than zero it will go ahead and execute the rest of the script.

将这段代码添加到顶部以验证是否有要返回的行。 如果它大于零,它将继续执行脚本的其余部分。


IF (SELECT COUNT(*) FROM dbo.Employe WHERE EmploymentStatus = 0)> 0
beginexec msdb.dbo.sp_send_dbmail
@profile_name = 'QA_Notification’,
@recipients = ‘human_resources@company.com’
@subject = ‘Employment Status’,
@query = ' SELECT Name, EmploymentStatus, StartDate FROM dbo.Employee
WHERE EmploymentStatus = 0’,
@attach_query_result_as_file = 1,
@query_attachment_filename = 'EmploymentStatus.csv'
End

Create a SQL Agent job, schedule it and make this piece of code a step. This method is quite versatile as you can use it for more than just sending records and reports to users. You can create custom alerts for yourself (the DBA)! Be creative, query DMV’s or whatever metrics you want, if they reach a certain threshold have the job email you.

创建一个SQL Agent作业,对其进行计划,并使这段代码成为一个步骤。 该方法用途广泛,不仅可以将记录和报告发送给用户,还可以使用。 您可以为自己(DBA)创建自定义警报! 要有创造力,请查询DMV或您想要的任何指标,如果达到一定阈值,请向您发送工作电子邮件。

Furthermore, you can go ahead and encompass the code into a stored procedure with parameters to make things even easier for yourself. The code would be cleaner, and a lot more flexible depending on what you want the parameters to be. You can even add in some error handling if you’d like.

此外,您可以继续将代码包含在带有参数的存储过程中,以使事情变得更轻松。 根据您想要的参数,代码将更简洁,并且更具灵活性。 如果愿意,您甚至可以添加一些错误处理。

As you can see, the possibilities are endless.

如您所见,可能性是无限的。

Before I conclude this post, I want to quickly touch on SQL Server Job Ownership. Who should “own” a SQL Agent Job and why does it matter?

在结束本文之前,我想快速介绍一下SQL Server作业所有权。 谁应该“拥有” SQL Agent Job,为什么重要?

When a SQL Server Agent Job executes, it will use the server’s own credentials to log into a session. Then it will switch the login of the session to the account that owns the SQL Server Agent job that is currently running. You can have a job potentially run under the incorrect security context. This can result in failures and strange entries into the SQL server log. (Well not strange to SQL server, but strange to whoever is sifting through them). Let’s say that SQL server defaulted to a regular employee username to execute a job and then that employee leaves the company. The job will start failing and the DBA has another problem to fix. This could be a disaster if that account owned many jobs that could include backups, data loads etc…As you can see, it would be quite a mess.

执行SQL Server代理作业时,它将使用服务器自己的凭据登录会话。 然后,它将会话的登录名切换到拥有当前正在运行SQL Server代理作业的帐户。 您可能有可能在不正确的安全上下文下运行作业。 这可能会导致失败和进入SQL Server日志的奇怪条目。 (对SQL Server来说并不奇怪,但是对筛选它们的人来说却很奇怪)。 假设SQL Server默认使用常规员工用户名执行工作,然后该员工离开公司。 作业将开始失败,并且DBA还要解决另一个问题。 如果该帐户拥有许多工作,其中可能包括备份,数据加载等,那将是一场灾难。正如您所看到的,这将是一团糟。

It is best to have a dedicated service account that is a member of the fixed sysadmin server role in SQL server take ownership of all SQL Jobs.

最好有一个专用服务帐户,该帐户是SQL Server中固定sysadmin服务器角色的成员,并拥有所有SQL作业的所有权。

It’s a good idea to get in the habit of setting this option upon creating a new job. When in the job properties simply go to the General menu and look at “Owner”. If it’s not already set to the right account simply click the box next to the field and change it. In this example, the owner is SA (or you can use the service account for SQL Server or SQL Agent).

养成在创建新工作时设置此选项的习惯是一个好主意。 在作业属性中时,只需转到常规菜单,然后查看“所有者”。 如果尚未将其设置为正确的帐户,只需单击该字段旁边的框并进行更改。 在此示例中,所有者是SA(或者您可以将服务帐户用于SQL Server或SQL Agent)。

If you want to check who owns the all SQL jobs on your servers you can create a query that pulls data from the msdb.dbo.sysjobs and join it to the master.syslogins table. I’ve used something like this in the past:

如果要检查谁拥有服务器上所有SQL作业,可以创建一个查询,该查询从msdb.dbo.sysjobs中提取数据并将其联接到master.syslogins表中。 我过去曾使用过类似的方法:


select
j.name AS [JobName],
l.name AS [LOGIN]from  [msdb].[dbo].[sysjobs] AS J join master.sys.syslogins AS l on j.owner_sid = l.sid

And if you get creative, you can make an alert for yourself using methods from the first part of this post. See the flexibility that we have now?

而且,如果您很有创造力,则可以使用本文第一部分中的方法来为自己发出警报。 看到我们现在拥有的灵活性吗?

For more information regarding SQL Agent account settings please feel free to go here

有关SQL代理帐户设置的更多信息,请随时转到此处

I hope that you found the information in this post useful and that you can take the general ideas to create customized solutions for yourself. Please feel free to share your creative solutions in the comments below or email me directly! I would like to hear from you!

我希望您发现这篇文章中的信息有用,并希望您可以采用一般思路为自己创建定制的解决方案。 请随时在下面的评论中分享您的创意解决方案,或直接给我发送电子邮件! 我希望收到您的来信!

参考资料 (References)

  • Configure Database Mail配置数据库邮件
  • sp_send_dbmail (Transact-SQL)sp_send_dbmail(Transact-SQL)
  • Select an Account for the SQL Server Agent Service为SQL Server代理服务选择一个帐户

翻译自: https://www.sqlshack.com/have-your-database-server-talk-to-you-send-emails-directly-from-sql-agent-jobs/

让您的数据库服务器与您对话:直接从SQL Agent Jobs发送电子邮件相关推荐

  1. 服务器系统坏了如何导出sql数据库,服务器系统坏了如何导出sql数据库

    服务器系统坏了如何导出sql数据库 内容精选 换一换 PostgreSQL支持逻辑备份.您可使用pg_dump逻辑备份功能,导出备份文件,再通过psql导入到RDS中,实现将PostgreSQL的数据 ...

  2. 数据库服务器 之 Postgresql备份和恢复------SQL转储篇

    作者:小P 来自:LinuxSir.Org 摘要: 和任何包含珍贵数据的东西一样,PostgreSQL 数据库也应该经常备份.备份PostgreSQL数据库有三种方法,各种方法有利有弊,本文先讲一下S ...

  3. python自建邮件服务器,9行自定义函数教你用Python发送电子邮件!

    作者 l 刘顺祥 来源 l 数据分析1480 前言 大概是在两三个月前,陆续有几位在职朋友问我如何使用Python发送邮件,说心里话这方面的操作在我之前的工作履历中真的没有碰到,所以我没有很好地帮助他 ...

  4. 如何查找数据库服务器ip_多服务器管理–查找数据库服务器

    如何查找数据库服务器ip Every organization has at least one of those guys. You are the guy if you have been wit ...

  5. 与数据库服务器通讯协议出错,与数据库服务器通讯异常

    与数据库服务器通讯异常 内容精选 换一换 华为云提供两种连接方式通过SQL Server客户端连接实例:非SSL连接和SSL连接.其中,SSL连接实现了数据加密功能,具有更高的安全性.安装SQL Se ...

  6. SharePoint 2010的数据库服务器实例默认为sqlserver2

    打开SQL Server Management Studio, 发现默认实例MSSQLSERVER中竟然找不到一个SharePoint 2010的数据库. 打开SharePoint 2010管理中心, ...

  7. SqlServer 数据库服务器运用

    1.压缩数据库日志文件 当数据库服务器满了之后,可用以下sql进行空间释放. USE [master] GO ALTER DATABASE AFMS SET RECOVERY SIMPLE WITH ...

  8. asp数据库服务器端连接错误信息,主数据库连接出错,请检查数据库连接字符串!...

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 我用的是小旋风asp服务器,运行后,显示:主数据库连接出错,请检查数据库连接字符串! 请问各位大侠那里出错了?? conn.asp里面的代码是: Dim  ...

  9. mysql查询数据库ppt_数据库与数据库服务器.ppt

    <数据库与数据库服务器.ppt>由会员分享,可在线阅读,更多相关<数据库与数据库服务器.ppt(35页珍藏版)>请在人人文库网上搜索. 1.企业网,朱加强 W,作业,画一个网络 ...

最新文章

  1. Android属动画ObjectAnimator和ValueAnimator应用
  2. ECharts Tooltip
  3. python下载库报错_下载python中Crypto库报错:ModuleNotFoundError: No module named ‘Crypto’的解决...
  4. spark 应用程序性能优化:12 个优化方法
  5. RPC(远程过程调用)
  6. tomcat之一:指定tomcat运行时JDK版本
  7. AnnotationUtils
  8. Orcale分析函数OVER(PARTITION BY... ORDER BY...)的讲解
  9. 基于sklearn分析特征工程(特征预处理、特征选择、降维)
  10. 前端js代码多文件混淆
  11. 09年最好看的电影大全_09年最经典的电影大全
  12. 程序员年薪30万,被准丈母娘各种刁难,网友说:分手吧!
  13. wim工具扫描linux磁盘,[V1.30.2011.501版]WimTool -- Wim文件的图形视窗处理工具[无忧首发]...
  14. 专业图形卡测试软件,专业卡能玩游戏么?实测很是意外
  15. PE结构学习(4)_节的操作
  16. 打印机可以打印不能扫描怎么弄_打印机无法扫描怎么解决 打印机无法扫描相关介绍【解决方法】...
  17. Java 对象排序完整版
  18. iphone分辨率终极指南(含iphone6/6+)
  19. 2020 - 2021 年 Web 前端最新导航 - 前端学习资源分享前端面试资源汇总
  20. 哲理短文-人生什么最重要

热门文章

  1. 从浏览器输入地址到渲染出网页这个过程发生了什么?
  2. Django中@login_required用法简介
  3. AtCoder 杂题训练
  4. netstat 查看端口
  5. 站立会议10--个人总结
  6. 将一个字符类型转换为字符串类型
  7. 如何打印出lua里table的内容
  8. CodeProject - 在C#使用SHGetFileInfo获取(管理)文件或者文件夹图标(C#封装Win32函数的一个例子)...
  9. 数据可视化js框架 d3.js入门
  10. 【Vue2.0】—解决页面闪烁的问题(八)