【问题标题】:ASP.NET Execute SQL Server stored procedure multiple times asyncASP.NET 多次异步执行 SQL Server 存储过程
【发布时间】:2017-04-04 15:28:44
【问题描述】:

我正在通过 ASP.NET 调用存储过程,现在我尝试将其异步调用 200 次,我尝试通过添加事务来执行此操作,但是它不起作用,这是我的代码:

try
{
    using (connection = new SqlConnection(connectionString))
    {
        connection.Open();
        transaction = connection.BeginTransaction();

        for (int i = 0; i < 200; i++)
        {
            using (SqlCommand command = new SqlCommand("TimeSlotAppointments", connection))
            {
                command.Transaction = transaction;

                command.CommandType = CommandType.StoredProcedure;

                SqlParameter parameter1 = command.Parameters.Add("@StartTime", SqlDbType.DateTime);
                parameter1.Direction = ParameterDirection.Input;
                parameter1.Value = DateTime.Now;

                command.ExecuteNonQuery();
            }
        }

        transaction.Commit();
    }
}
catch (SqlException e)
{
    Console.Write(e);
    transaction.Rollback();
}
finally
{
    connection.Close();
    connection.Dispose();
}

我将当前日期和时间作为参数传递,当我在 SQL Server 中检查结果时,我希望 @StartTime 相同,但它们不是,关闭,但每条记录的毫秒数会增加,我是不是走错了路?我想要完成的是同时执行存储过程 200 次。

【问题讨论】:

  • 如果您希望所有记录的 DateTime 相同,则将DateTime.Now 存储在循环外的变量中,并将其用于parameter1.Value
  • 当你调用DateTime.Now 200 次时,为什么你会期望@StartTime 是一样的?时间过去了......但是:这段代码实际上试图做什么?您似乎不太可能希望使用相同的参数运行完全相同的 SQL - 200 次。此外,您实际上并没有将其称为异步(“现在我尝试将其称为 200 次异步”)
  • 事务与异步有什么关系?交易用于做相反的。强制多个并发命令按顺序运行
  • 如果你想执行同一个sproc N次,创建sproc一次然后更改参数值N次:for (i=0;i&lt;200;i++){parameter1.Value=someNewValue;cmd.ExecuteNonQuery();}更好的 解决方案是完全避免循环。 sproc 有什么作用,为什么不一次传递所有需要的值?

标签: c# asp.net sql-server stored-procedures


【解决方案1】:

开始时间值不同,因为您在循环中分配值inside,并且在每次迭代中,时间都发生了变化(您提到的几毫秒)。如果要对所有调用使用相同的值,则需要将循环外的时间戳存储在一个变量中,并在循环中使用该值。 你的代码应该是这样的:

try
{
    using (connection = new SqlConnection(connectionString))
    {
        connection.Open();
        transaction = connection.BeginTransaction();
        var startTime = DateTime.Now; // I added this line 

        for (int i = 0; i < 200; i++)
        {
            using (SqlCommand command = new SqlCommand("TimeSlotAppointments", connection))
            {
                command.Transaction = transaction;

                command.CommandType = CommandType.StoredProcedure;

                SqlParameter parameter1 = command.Parameters.Add("@StartTime", SqlDbType.DateTime);
                parameter1.Direction = ParameterDirection.Input;
                parameter1.Value = startTime;  // I changed this line

                command.ExecuteNonQuery();
            }
        }

        transaction.Commit();
    }
}
catch (SqlException e)
{
    Console.Write(e);
    transaction.Rollback();
}
finally
{
    connection.Close();
    connection.Dispose();
}

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多