本文給出一個(gè)使用實(shí)例,結(jié)合存儲(chǔ)過程和Job來實(shí)現(xiàn)定時(shí)從數(shù)據(jù)庫(kù)發(fā)送郵件:
1、創(chuàng)建存儲(chǔ)過程,在新建的存儲(chǔ)過程中調(diào)用sp_send_dbmail存儲(chǔ)過程(注:代碼中的\'只是添加代碼時(shí)自動(dòng)添加的轉(zhuǎn)義字符,實(shí)質(zhì)代碼中只有單引號(hào))
代碼如下:
Create PROCEDURE [dbo].[sp_send_error_alert]
AS
declare
@v_contentnvarchar(max),
@v_mail_tonvarchar(500),
@v_bodynvarchar(max),
@v_titilenvarchar(100)
,@v_br_idnvarchar(50)
,@v_installmentsnvarchar(10)
,@v_remarknvarchar(100)
BEGIN
SETNOCOUNTON;
set@v_titile=\'測(cè)試郵件內(nèi)容標(biāo)題;
set@v_content=\'\';
DECLAREcursor_repaymentCURSORFOR
SELECT
br_id
,installments
,remark
fromdw_account_repaymentt
where
status!=1
andis_del=0
orderbyt.add_datetimedesc;
OPENcursor_repayment
FETCHNEXTFROMcursor_repaymentINTO
@v_br_id--標(biāo)ID
,@v_installments--期數(shù)
,@v_remark--錯(cuò)誤描述
WHILE@@FETCH_STATUS=0
BEGIN
set@v_content=@v_content+\'<tr><td>\'+@v_br_id+\'</td>\'+\'<td>\'+@v_installments+\'</td>\'+\'<td>\'+@v_remark+\'</td></tr>\';
fetchnextfromcursor_repaymentinto
@v_br_id--標(biāo)ID
,@v_installments--期數(shù)
,@v_remark--錯(cuò)誤描述
end;
CLOSEcursor_repayment;--關(guān)閉游標(biāo)
DEALLOCATEcursor_repayment;--清空游標(biāo)
ifLEN(@v_content)>0
begin
SET@v_body=\'<html><H1>自動(dòng)還款所有異常列表</H1><bodybgcolor=white><tableborder=1><tr><th>標(biāo)ID</th><th>期數(shù)</th><th>錯(cuò)誤描述</th></tr>\'
SET@v_body=@v_body+@v_content+\'</table></body></html>\'
EXECmsdb.dbo.sp_send_dbmail
@recipients=N\'接收用戶地址1@qq.com;接收用戶地址2@qq.com\',@body=@v_body,@body_format=\'HTML\'
,@subject=@v_titile,@profile_name=\'上一節(jié)點(diǎn)的配置文件名(db_profiler)\
創(chuàng)建Job(SqlServer代理->作業(yè)),設(shè)置執(zhí)行參數(shù),定時(shí)執(zhí)行此存儲(chǔ)過程,即可實(shí)現(xiàn)定時(shí)發(fā)送郵件效果。
更多信息請(qǐng)查看IT技術(shù)專欄