2015年8月7日 星期五

以SQL Server發送郵件

sp_send_dbmail (Transact-SQL)

 Sends an e-mail message to the specified recipients. The message may include a query result set, file attachments, or both. When mail is successfully placed in the Database Mail queue, sp_send_dbmail returns the mailitem_id of the message. This stored procedure is in the msdb database.

 reference from : https://msdn.microsoft.com/en-us/library/ms190307.aspx

Sending an e-mail message with the results of a query

This example sends an e-mail message to Dan Wilson using the e-mail address danw@Adventure-Works.com. The message has the subject Work Order Count, and executes a query that shows the number of work orders with a DueDate less than two days after April 30, 2004. Database Mail attaches the result as a text file.
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Adventure Works Administrator',
    @recipients = 'danw@Adventure-Works.com',
    @query = 'SELECT COUNT(*) FROM AdventureWorks2012.Production.WorkOrder
                  WHERE DueDate > ''2004-04-30''
                  AND  DATEDIFF(dd, ''2004-04-30'', DueDate) < 2' ,
    @subject = 'Work Order Count',
    @attach_query_result_as_file = 1 ;



Note1. Enable the Database Mail extended stored procedures.

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Database Mail XPs', 1;
GO
RECONFIGURE
GO

reference from : https://technet.microsoft.com/en-us/library/ms191189(v=sql.110).aspx

Note2. Create database mail profile via wizard.

2015年8月4日 星期二

遞迴(Recursive)

遞迴(Recursion)


一個還沒執行完又呼叫自己,符合條件時才停止的副程式。
一個不停呼叫自己直到滿意為止的程式。

初學時,總覺得莫名其妙,明明迴圈就可以處理了,為何要改成這種沒寫好就會陷入無窮迴圈的模式...

遇過有人看到所寫的程式寫法太"單純",沒用到遞回就質疑學藝不精...

洪教授寫了一篇愚公移山與遞迴,清楚說明了這跟效率與程式可讀性有關,

除此之外,個人認為還有Programmer 習慣與思考迴路的影響...

舉例來說:
假設每個月存3000元,隔月比上個月多存100元,計算存到n個月後會有多少錢?
也就是第1個月存3000元、第2個月存3100、第3個月存3200...

迴圈寫法
///<param name="n">計算月數</param>
///<param name="inc">每月增額</param>
///<param name="deposit">存款</param>
///<returns></returns>
protected int recursive(int n, int inc, int deposit)
{
    int mny = 0;
    for (int i = 1; i <= n; i++)
    {
        mny = mny + deposit + inc * (i - 1);
    }
    return mny;
}

遞迴寫法
///<param name="n">計算月數</param>
///<param name="inc">每月增額</param>
///<param name="deposit">存款</param>
///<returns></returns>
protected int recursive(int n, int inc, int deposit)
{
    return (n == 1) ? deposit : deposit + recursive(n - 1, inc, deposit + inc);
}