汇总SSIS中的列并发送电子邮件

时间:2017-05-17 14:54:35

标签: c# sql-server ssis

我有一张表,我需要总结2列(薪水和奖金)并通过电子邮件发送给他们  关闭使用SSIS。我以某种方式设法编写了一个脚本来发送电子邮件但无法在C#中汇总2列。

    public void Main()

            {
                String SendMailFrom = Dts.Variables["EmailFrom"].Value.ToString();
                String SendMailTo = Dts.Variables["EmailTo"].Value.ToString();
                MailMessage msg = new MailMessage();
                msg.To.Add(new MailAddress("bbb"));
                msg.From = new MailAddress("ccc");
                msg.Body = "Process is completed successfully.
                               1) Sum of Salary is 1234 
                               2)Sum of Bonus is 1234
                               3) Count of distinct Accounts is 123";//This is the requirement
                msg.Subject = "XYZ PROCESS";
                msg.IsBodyHtml = true;
                DataTable dtResults = new DataTable();
                OleDbConnection dbConnection = new OleDbConnection("xxx");
                SmtpClient client = new SmtpClient();
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential("xxx");
                client.Port = 587; 
                client.Host = "smtp.office365.com";
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.EnableSsl = true;
                try
                {
                    dbConnection.Open();

                    if (dbConnection.State == ConnectionState.Open)
                    {
                        OleDbCommand dbCommand = dbConnection.CreateCommand();
                        dbCommand.CommandType = CommandType.Text;
                        dbCommand.CommandText = "SELECT SUM([Salary]),Sum([Bonus]) FROM table";
                        OleDbDataReader dbReader = dbCommand.ExecuteReader();

                        if (dbReader.HasRows)
                            dtResults.Load(dbReader);

                        string theSum = dtResults.Rows[0]["TOTAL"].ToString();
                        dbReader.Close();
                        dbConnection.Close();
                        client.Send(msg);
                        MessageBox.Show("Email was Successfully Sent ");

                    }
                }



                //try
                //{
                //    client.Send(msg);
                //    MessageBox.Show("Email was Successfully Sent ");
                //}
                catch (Exception ex)
                {
                    throw new Exception("Unable to execute query as requested.", ex);
                    MessageBox.Show(ex.ToString());
                }

                //{
                //    MessageBox.Show(ex.ToString());
                //}
            }

            #region ScriptResults declaration
            /// <summary>
            /// This enum provides a convenient shorthand within the scope of this class for setting the
            /// result of the script.
            /// 
            /// This code was generated automatically.
            /// </summary>
            enum ScriptResults
            {
                Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
                Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
            };
            #endregion

        }
    }

我不是编写C#脚本的专家,非常感谢帮助

3 个答案:

答案 0 :(得分:2)

与往常一样,将问题分解为更小的单位,直到找到可以解决的问题为止。

我会创建一个名为BuildMessageBody的方法。这将运行您的查询并切出您想要的元素,然后使用string.Format方法按顺序位置将您想要的值替换为您的消息。

public string BuildMessageBody()
{
    // Create a message template that will 
    string template = @"Process is completed successfully.
                   1) Sum of Salary is {0}
                   2) Sum of Bonus is {1}
                   3) Count of distinct Accounts is {2}";
    string query = @"SELECT SUM(T.[Salary]) AS TotalSalary, Sum(T.[Bonus]) AS TotalBonus, COUNT(DISTINCT T.AccountNumber) AS UniqueAccounts FROM table AS T";

    string totalSalary = string.Empty;
    string totalBonus = string.Empty;
    string uniqueAccounts = string.Empty;
    string body = string.Empty;

    using(OleDbConnection dbConnection = new OleDbConnection("xxx"))
    {
        dbConnection.Open();
        using (OleDbCommand cmd = new OleDbCommand(query, dbConnection))
        {
            cmd.CommandType = System.Data.CommandType.Text;
            using (OleDbDataReader  reader = cmd.ExecuteReader())
            {
                // This should only ever yield one row due to aggregation in source query
                // But this implementation will result in the last row (arbitrary source sorting)
                // being preserved
                while (reader.Read())
                {
                    // Access by ordinal position
                    totalSalary = reader[0].ToString();
                    totalBonus = reader[1].ToString();
                    uniqueAccounts = reader[2].ToString();
                }
            }
        }

        // At this point, we should have results
        body = string.Format(template, totalSalary, totalBonus, uniqueAccounts);
    }

    return body;
}

您的原始代码会将msg.Body的分配替换为

msg.Body = BuildMessageBody();

然后您可以删除ScriptMain(try块)中的所有数据访问代码,但保留client.Send(msg);或者您永远不会发送电子邮件。

答案 1 :(得分:1)

我猜你在这行代码中出现错误,因为查询中没有TOTAL列:

string theSum = dtResults.Rows[0]["TOTAL"].ToString();

修改你的SQL查询,它可能有用(你需要为这两个总和添加一个总额)我刚为奖金添加:

dbCommand.CommandText = "SELECT SUM([Salary]),Sum([Bonus]) as TOTAL FROM table";

而且正如billinkc所提到的,你在电子邮件中永远不会对theSum做任何事情。

答案 2 :(得分:1)

你需要提供你的SUM&#34;列&#34;名。就像里克所说,你引用了&#34; TOTAL&#34;列但没有TOTAL列。您正在查询2个总和/总计,因此它们都需要名称,您需要同时获取代码并在电子邮件中格式化它们,无论您想要什么。

dbCommand.CommandText = "SELECT SUM([Salary]) As SalaryTotal, Sum([Bonus]) As BonusTotal FROM table";

string theSum1 = dtResults.Rows[0]["BonusTotal"].ToString();
string theSum2 = dtResults.Rows[0]["SalaryTotal"].ToString();