简体   繁体   English

T-SQL查询结果转换为变量

[英]T-SQL query result into variable

I am trying to assign the result of a SQL query into a variable but running into issues. 我正在尝试将SQL查询的结果分配给变量,但遇到问题。

Here is my query: 这是我的查询:

use db
SELECT name
,ID
,pID
,pName
,group
FROM mName as m
INNER JOIN pID_Check AS p ON m.ID= p.pID
WHERE p.pName NOT LIKE m.name

Query works fine however I'm trying to schedule it to run hourly via SQL Server Agent and email on results. 查询工作正常,但是我试图安排它通过SQL Server代理每小时运行一次,并通过电子邮件发送结果。
Most of the time the query will not return any data but in the event there are rows I need it to email out. 在大多数情况下,查询不会返回任何数据,但是如果有行,我需要它来通过电子邮件发送出去。
Essentially need values of the row added to @results variable and email triggered only if @results not null 本质上需要将行的值添加到@results变量中,并且仅在@results不为null时触发电子邮件

SET @sub = 'Subject' 
EXEC msdb.dbo.sp_send_dbmail 
@profile_name = 'Profile',
@recipients = 'email@email.com;',
@body = @results,
@subject = @sub

You seem to want to send the result set to a mail recipient - while that is possible, I'm not aware of being possible to stick into the body in the method which you have attempted. 您似乎想将结果集发送给邮件收件人-虽然这是可能的,但我不知道有可能以您尝试的方法粘在正文中。
It can be included as an attachment via another property of SP_SEND_DBMAIL . 可以通过SP_SEND_DBMAIL另一个属性作为附件包含在内。 Please see your example below, modified to include the result set as an attachment: 请参见下面的示例,将其修改为包括结果集作为附件:

DECLARE @myquery varchar(max) = '
SELECT name
,ID
,pID
,pName
,group
FROM mName as m
INNER JOIN pID_Check AS p ON m.ID= p.pID
WHERE p.pName NOT LIKE m.name
'

SET @sub = 'Subject' 
EXEC msdb.dbo.sp_send_dbmail 
@profile_name = 'Profile',
@recipients = 'email@email.com;',
@body = @results,
@subject = @sub,
@query = @myquery,
@attach_query_result_as_file = 1,
@query_attachment_filename= 'MyFileName.csv';

All SP_SEND_DBMAIL properties can be seen here: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-send-dbmail-transact-sql 可以在这里查看所有SP_SEND_DBMAIL属性: https : SP_SEND_DBMAIL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM