2012-09-15 62 views
1

作業調度查詢我有一個假設發送每日收集報告基於20個不同的部門20級不同ID的作業調度程序。每個部門只會收到該部門的1份報告。這是我提出的查詢。電子郵件生成日報表

DECLARE @xml NVARCHAR(MAX) 
DECLARE @body NVARCHAR(MAX) 


SET @xml = CAST((select tm.name as 'td','',h.name as 'td','',h.account_number AS 'td','', 
SUM(bc.total_amount) AS 'td' 
FROM MJP.dbo.tbl_bank_collection bc, 
MJP.dbo.tbl_div_type_master tm, 
MJP.dbo.tbl_div_header h 
where bc.type_id = tm.id  
and bc.header_id = h.id  
and bc.transaction_date = '06-12-2012' 
and bc.div_id in (select d.id  
from tbl_div d, tbl_bank_collection bc  
where bc.div_id = d.id  
group by d.id)  
group by tm.name, h.name,h.account_number with rollup  
having grouping(h.name) = 1 or  
GROUPING(h.account_number) = 0  
FOR XML PATH('tr'), ELEMENTS) AS NVARCHAR(MAX)) 
SET @body ='<html><i>Collection Report</i>  
<body bgcolor=red><table border = 1><tr><th>Type Name  
<th>Header Name</th><th>Account Number</th>  
<th>Total Amount</th></tr>'  
SET @body = @body + @xml +'</table></body></html>' 
EXEC msdb.dbo.sp_send_dbmail  
@profile_name='alkesh mail',  
@body_format ='HTML',  
@recipients='[email protected];[email protected]',  
@subject='Daily Report',  
@[email protected]  


---------------------------------------------------------------------------------------- 

現在我想計算之後的特定divison的最後一筆金額,並應在未來師」身份證生成的下一個報告分裂報告。

任何建議或澄清!

回答

0

我假設企業政治有你的SQL Server中的限制,因爲串聯XML的電子郵件報告是什麼SQL服務器是專爲。

我個人有一個服務的可執行文件(Windows服務,或只是一個控制檯應用程序通過任務調度器調用,等等。)與代碼(例如C#)認爲:

  1. 獲取只是數據形式SQL Server,通過一個divisionId參數來獲取的報告只是那個分部。

  2. 打開XML模板文件並插入數據。

  3. 從SQL Server請求該部門的用戶列表,並通過電子郵件向列表中的每個人發送電子郵件。

  4. 重複每個部門。

說了這麼多,你可以用存儲過程來做到這一點,使用循環。你可以使用遊標(yuck),但我總是更喜歡這些結構:(注意,在RDBMS中循環是真的要避免的事情,它非常依賴於你的特定情況)

declare @divisionId int = (select min(divisionId) from tbDivisions) 
declare @userId int = (min(userId) from users where divisionId = @divisionId) 
declare @xml nvarchar(max) 

while divisionId is not null 
begin 
    exec your_report_stored_procedure @division = @divisionId, output @xml = @xmlOut 

    while @userId is not null 
    begin 
     exec your_email_tored_procedure @userId = @userId, @xmlIn = @xml 
     select @userId = min(userId) from users where divisionId = @divisionId and userId > @userId 
    end 

    select @divisionId = min(divisionId) from tbDivisions where divisionId > @divisionId 
end