Thursday, August 8, 2024

Tạo report gửi email tự động với MSSQL

 

Tạo một câu lệnh gửi email

Step 1:

Tạo mail database profile như hình bên dưới




Bước 2:

Copy câu lệnh bỏ trực tiếp vào  cửa sổ đang mở bước số 5, nhơ thay đổi địa chỉ email người nhập vào



 

 

DECLARE @tableHTML NVARCHAR(MAX);

DECLARE @dateSync VARCHAR(200) = CONVERT(Varchar,getdate());

SET @tableHTML = 'This is an automatic email that is send from the system.<br>

The following is a table of stores which synchronized data to system.<br>'

+N'<H1>Check Synchronized at '+@dateSync+'</H1>' + N'<table border="1">'

    + N'<tr style="font-family:Arial;font-size:14px;padding:10px 5px;width:100%;background-color:#ff9900;color:#333">

            <th>Id</th>

            <th>StoreName</th>'

    + N'<th>Sync_Check</th>

            <th>Date_Check</th></tr>'

    + CAST(( SELECT DISTINCT td=(BRPOSStoreID),'',

                                                                                    td=(BRPOSStoreName),''

                        ,td=(CASE WHEN FORMAT(BRRecheckSyncFromPOSToDate,'dd/MM/yyyy') IS NULL THEN N'CHƯA ĐỒNG BỘ'

                                    ELSE N'ĐÃ ĐỒNG BỘ' END),''

                        ,td=(FORMAT(getdate(),'dd/MM/yyyy')),''

                        FROM BJStoreName

                        left join BJ_BRRecheckSyncFromPOSs

                        on BJStoreName.BRPOSStoreName=BRRecheckSyncFromPOSStoreName and FORMAT(BRRecheckSyncFromPOSToDate,'dd/MM/yyyy') = FORMAT(getdate()-1, 'dd/MM/yyyy')

                                    where AAStatus='Alive' and BRPOSStoreID in (2,3,5,7,9,11,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,29,30)

                                    Order by (CASE WHEN FORMAT(BRRecheckSyncFromPOSToDate,'dd/MM/yyyy') IS NULL THEN N'CHƯA ĐỒNG BỘ'

                                    ELSE N'ĐÃ ĐỒNG BỘ' END)  

          FOR XML PATH('tr'),

                TYPE

            ) AS NVARCHAR(MAX))

    + N'</table> <br>'

            +N'Please let me know if you have any questions or need further clarification.<br><br>'

            +N'Thanks & regards,<br>'

            +N'IT Department';

 EXEC msdb.dbo.sp_send_dbmail

            @profile_name = 'Email_Automation',

            @recipients =nhập Email người nhận tại đây’,

    @subject = 'Report daily check synchronized from store to PosHead',

    @body = @tableHTML,

    @body_format = 'HTML';

Bước 3:  Tạo lịch để chạy SQL này, vào phần schedule , phần này dễ anh chị em có thể search trên google

Cuối cùng chạy thử 1 lệnh chúng ta thấy kết quả, anh chị có thể thay đổi format cho báo cáo đẹp hơn, phần này có thể áp dụng làm báo cáo trực tiếp bằng SQL cũng được.



 

Chúc mọi người thành công







No comments:

Post a Comment