c# - 脚本任务 C# 中的命令超时

标签 c# sql-server ssis etl script-task

我收到此超时错误:

Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding

脚本任务执行存储过程需要一些时间。如果我更改存储过程中的参数以检索更少的数据,那么它可以正常工作。所以我假设我必须增加代码中的连接超时。但我不知道我到底应该在哪里做?

我尝试在连接管理器中更改连接超时 - 但没有帮助。

enter image description here

我也尝试过这个:

cmd.CommandTimeout = 500;

但是仍然没有成功。

我想我需要在代码中的某个地方这样做:

public void Main()
        {
            string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
            DateTime startDate = DateTime.Now.AddMonths(-1).AddDays(1 - DateTime.Now.Day);
            DateTime endDate = startDate.AddMonths(1).AddDays(-1);
            //var now = DateTime.Now;
            //var firstDayCurrentMonth = new DateTime(now.Year, now.Month, 1);
            //var lastDayLastMonth = firstDayCurrentMonth.AddDays(-1);
            try
            {
                //Declare Variables

                // string ExcelFileName = Dts.Variables["User::ExcelFileName"].Value.ToString() +" "+ String.Format("{0:M-d-yyyy}", endDate);
                string ExcelFileName = Dts.Variables["User::NewExcelFileName"].Value.ToString();
                string FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
                string StoredProcedureName = Dts.Variables["User::StoredProcedureName"].Value.ToString();
                string SheetName = Dts.Variables["User::SheetName"].Value.ToString();
                string connStringDB = "MyConnString";
                string excelConn = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}{1};Mode=ReadWrite;Extended Properties='Excel 12.0 Xml;HDR=YES';", FolderPath, ExcelFileName);

                using (var conn = new SqlConnection(connStringDB))
                using (var command = new SqlCommand(StoredProcedureName, conn)

                {
                    CommandType = CommandType.StoredProcedure
                })
                {
                    conn.Open();


                    string queryString = String.Format("EXEC {0}", StoredProcedureName);

                    SqlDataAdapter adapter = new SqlDataAdapter(queryString, conn);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);

                    //Get Header Columns
                    string TableColumns = "";
                    // Get the Column List from Data Table so can create Excel Sheet with Header
                    foreach (DataTable table in ds.Tables)
                    {
                        foreach (DataColumn column in table.Columns)
                        {
                            TableColumns += column + "],[";
                        }
                    }
                    conn.Close();

                    // Replace most right comma from Columnlist
                    //TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
                    TableColumns = ("[" + TableColumns.Replace(",", " text,").TrimEnd(','));
                    TableColumns = TableColumns.Remove(TableColumns.Length - 2);

                    //Use OLE DB Connection and Create Excel Sheet
                    using (OleDbConnection connODB = new OleDbConnection(excelConn))
                    {
                        connODB.Open();
                        OleDbCommand cmd = new OleDbCommand();
                        cmd.Connection = connODB;
                        cmd.CommandTimeout = 500; //Entered by Oleg

                        cmd.CommandText = String.Format("Create table {0} ({1})", SheetName, TableColumns);
                        cmd.ExecuteNonQuery();

                        foreach (DataTable table in ds.Tables)
                        {
                            String sqlCommandInsert = "";
                            String sqlCommandValue = "";
                            foreach (DataColumn dataColumn in table.Columns)
                            {
                                sqlCommandValue += dataColumn + "],[";
                            }

                            sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
                            sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
                            sqlCommandInsert = String.Format("INSERT INTO {0} ({1}) VALUES (", SheetName, sqlCommandValue);
                            int columnCount = table.Columns.Count;
                            foreach (DataRow row in table.Rows)
                            {
                                string columnvalues = "";
                                for (int i = 0; i < columnCount; i++)
                                {
                                    int index = table.Rows.IndexOf(row);
                                    var a = table.Rows[index].ItemArray[i].ToString().Replace("'", "''");
                                    columnvalues += "'" + a + "',";
                                    //columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";

                                }
                                columnvalues = columnvalues.TrimEnd(',');
                                var command2 = sqlCommandInsert + columnvalues + ")";
                                cmd.CommandText = command2;
                                cmd.ExecuteNonQuery();
                            }

                        }
                        conn.Close();
                    }


                }

                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch (Exception exception)
            {

                // Create Log File for Errors
                using (StreamWriter sw = System.IO.File.CreateText(Dts.Variables["User::FolderPath"].Value.ToString() + "\\" +
                    Dts.Variables["User::ExcelFileName"].Value.ToString() + datetime + ".log"))
                {
                    sw.WriteLine(exception.ToString());
                    Dts.TaskResult = (int)ScriptResults.Failure;

                }
            }
        }
    #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

    }
}

最佳答案

尝试将命令超时设置为 0 而不是 500

cmd.CommandTimeout = 0;

您还必须设置 SQLAdapter 超时:

adapter.SelectCommand.CommandTimeout = 0;

基于official documentation

A value of 0 indicates no limit (an attempt to execute a command will wait indefinitely).

您的代码应如下所示:

public void Main()
        {
            string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
            DateTime startDate = DateTime.Now.AddMonths(-1).AddDays(1 - DateTime.Now.Day);
            DateTime endDate = startDate.AddMonths(1).AddDays(-1);
            //var now = DateTime.Now;
            //var firstDayCurrentMonth = new DateTime(now.Year, now.Month, 1);
            //var lastDayLastMonth = firstDayCurrentMonth.AddDays(-1);
            try
            {
                //Declare Variables

                // string ExcelFileName = Dts.Variables["User::ExcelFileName"].Value.ToString() +" "+ String.Format("{0:M-d-yyyy}", endDate);
                string ExcelFileName = Dts.Variables["User::NewExcelFileName"].Value.ToString();
                string FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
                string StoredProcedureName = Dts.Variables["User::StoredProcedureName"].Value.ToString();
                string SheetName = Dts.Variables["User::SheetName"].Value.ToString();
                string connStringDB = "MyConnString";
                string excelConn = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}{1};Mode=ReadWrite;Extended Properties='Excel 12.0 Xml;HDR=YES';", FolderPath, ExcelFileName);

                using (var conn = new SqlConnection(connStringDB))
                using (var command = new SqlCommand(StoredProcedureName, conn)

                {
                    CommandType = CommandType.StoredProcedure
                })
                {
                    conn.Open();


                    string queryString = String.Format("EXEC {0}", StoredProcedureName);

                    SqlDataAdapter adapter = new SqlDataAdapter(queryString, conn);
                    DataSet ds = new DataSet();
                    adapter.SelectCommand.CommandTimeout = 0;
                    adapter.Fill(ds);

                    //Get Header Columns
                    string TableColumns = "";
                    // Get the Column List from Data Table so can create Excel Sheet with Header
                    foreach (DataTable table in ds.Tables)
                    {
                        foreach (DataColumn column in table.Columns)
                        {
                            TableColumns += column + "],[";
                        }
                    }
                    conn.Close();

                    // Replace most right comma from Columnlist
                    //TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
                    TableColumns = ("[" + TableColumns.Replace(",", " text,").TrimEnd(','));
                    TableColumns = TableColumns.Remove(TableColumns.Length - 2);

                    //Use OLE DB Connection and Create Excel Sheet
                    using (OleDbConnection connODB = new OleDbConnection(excelConn))
                    {
                        connODB.Open();
                        OleDbCommand cmd = new OleDbCommand();
                        cmd.Connection = connODB;
                        cmd.CommandTimeout = 0; //Entered by Oleg

                        cmd.CommandText = String.Format("Create table {0} ({1})", SheetName, TableColumns);
                        cmd.ExecuteNonQuery();

                        foreach (DataTable table in ds.Tables)
                        {
                            String sqlCommandInsert = "";
                            String sqlCommandValue = "";
                            foreach (DataColumn dataColumn in table.Columns)
                            {
                                sqlCommandValue += dataColumn + "],[";
                            }

                            sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
                            sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
                            sqlCommandInsert = String.Format("INSERT INTO {0} ({1}) VALUES (", SheetName, sqlCommandValue);
                            int columnCount = table.Columns.Count;
                            foreach (DataRow row in table.Rows)
                            {
                                string columnvalues = "";
                                for (int i = 0; i < columnCount; i++)
                                {
                                    int index = table.Rows.IndexOf(row);
                                    var a = table.Rows[index].ItemArray[i].ToString().Replace("'", "''");
                                    columnvalues += "'" + a + "',";
                                    //columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";

                                }
                                columnvalues = columnvalues.TrimEnd(',');
                                var command2 = sqlCommandInsert + columnvalues + ")";
                                cmd.CommandTimeout = 0;
                                cmd.CommandText = command2;
                                cmd.ExecuteNonQuery();
                            }

                        }
                        conn.Close();
                    }


                }

                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch (Exception exception)
            {

                // Create Log File for Errors
                using (StreamWriter sw = System.IO.File.CreateText(Dts.Variables["User::FolderPath"].Value.ToString() + "\\" +
                    Dts.Variables["User::ExcelFileName"].Value.ToString() + datetime + ".log"))
                {
                    sw.WriteLine(exception.ToString());
                    Dts.TaskResult = (int)ScriptResults.Failure;

                }
            }
        }
    #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# - 脚本任务 C# 中的命令超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54521831/

相关文章:

c# - 如果数量在阈值内,则捕捉到角度

c# - 尝试使用托管访问连接 Azure DataLake 但出现未经授权的错误

sql-server - 将 varchar dd/mm/yyyy 转换为 dd/mm/yyyy 日期时间

sql-server - 无法将 SSIS 包部署到 Windows 10 Pro 上的 SQL Server 2016 Express

c# - 在 .net 中获取 facebook 广告 api 错误

c# - 检索选项卡标题内容

sql-server - 如何限制用户对特定架构(sql server)的 CREATE TABLE 访问?

sql-server - Sql Server 页面结构。 Fdata 长度是多少?

sql-server-2008 - 在不同时间使用不同参数执行相同的 SSIS 包

sql-server - 如何将多个SSIS包自动导入到Data Tools Solution?