我是存储过程新手。我试图通过读取表来发送邮件,并执行以下查询
create procedure mailtouser
as
declare @data varchar(max),
@user varchar(max)
as
set @data='set nocount on;select col_name from tbl_name where id=1;set nocount off;'
set @user='user@example.com'
set @query=
exec sp_send_dbmail
@profile_name = 'profile',
@recipients = @user,
@subject = 'automail',
@execute_query_database = 'database',
@query = @data;
end
end
exec mailtouser去
当执行这个脚本时,我收到邮件
col_name
------------------------------------------------------------------------------------------------------------
datas.
如何避免这个col_name和lines。
首先,您是否将数据库命名为[database]?应该像[AdventureWorks2012]。
第二步,执行查询并返回结果。如果您使用三部分符号[AdventureWorks2012].[Person].[Address].
,则不需要@execute_query_database。第三,这个选项还有其他参数。看一看
@query_result_header@query_result_width@query_result_separator@exclude_query_output
另一方面,如果您想完全控制,可以将正文格式更改为HTML。
在SET语句中运行查询,以按照您想要的方式格式化数据。
-- Send with embedded html table containing query data
DECLARE @VAR_HTML NVARCHAR(MAX) ;
SET @VAR_HTML =
N'<h1>Work Order Report<h1>' +
N'<table border="1">' +
N'<tbody><tr><th>Work Order ID</th><th>Product ID</th>' +
N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
N'<th>Expected Revenue</th></tr>' +
CAST ( ( SELECT td = wo.WorkOrderID, '',
td = p.ProductID, '',
td = p.Name, '',
td = wo.OrderQty, '',
td = wo.DueDate, '',
td = (p.ListPrice - p.StandardCost) * wo.OrderQty
FROM AdventureWorks2008R2.Production.WorkOrder as wo
JOIN AdventureWorks2008R2.Production.Product AS p
ON wo.ProductID = p.ProductID
WHERE DueDate > '2006-04-30'
AND DATEDIFF(dd, '2006-04-30', DueDate) < 2
ORDER BY DueDate ASC,
(p.ListPrice - p.StandardCost) * wo.OrderQty DESC
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX) ) +
N'</tbody></table>'
EXEC msdb.dbo.sp_send_dbmail
@recipients='john@craftydba.com',
@subject = 'Work Order List',
@body = @VAR_HTML,
@body_format = 'HTML' ;
真诚J