首页 > 解决方案 > SQL 更新语句显示 OldShippedDate == NewShippedDate(当我更改新的发货日期时)以尝试更新。抛出sql并发错误

问题描述

我正在尝试通过 C# 更改发货日期,然后过滤到 SQL Server 数据库。当我尝试更改日期时,我遇到了一个并发问题,说其他人正在访问数据库上的同一条记录。我在 C# 中使用了调试工具,并注意到旧ShippedDate的在通过更新客户方法时显示与新的发货日期相同。我试图通过代码,似乎无法找到不正确的地方。任何帮助将不胜感激。

如上所述,我已经非常广泛地使用了调试工具,并指出原始日期被更改为新日期。然后它导致我的计数 = 0,然后引发错误。

数据库连接良好,已显示成功。

这是有问题的代码:

public static bool UpdateOrder(Orders oldOrd, Orders newOrd)
{
        bool success = false; // did not update

        // connection
        SqlConnection connection = NORTHWNDDB.GetConnection();
        // update command
        string updateStatement =
            "UPDATE Orders SET " +
            "ShippedDate = @NewShippedDate " +
            "WHERE OrderID = @OldOrderID " + // identifies order
            "AND CustomerID = @OldCustomerID" + // ie. another user changed a value
            " AND OrderDate= @OldOrderDate" + // before update completed
            " AND RequiredDate= @OldRequiredDate" +
            " AND (ShippedDate= @OldShippedDate OR " + // either equal or both are null
            "     ShippedDate IS NULL AND @OldShippedDate IS NULL)";
        SqlCommand cmd = new SqlCommand(updateStatement, connection);
        if (newOrd.ShippedDate == null)
            cmd.Parameters.AddWithValue("@NewShippedDate", DBNull.Value);
        else
            cmd.Parameters.AddWithValue("@NewShippedDate", newOrd.ShippedDate);
        cmd.Parameters.AddWithValue("@OldOrderID", oldOrd.OrderID);
        cmd.Parameters.AddWithValue("@OldCustomerID", oldOrd.CustomerID);
        cmd.Parameters.AddWithValue("@OldOrderDate", oldOrd.OrderDate);
        cmd.Parameters.AddWithValue("@OldRequiredDate", oldOrd.RequiredDate);
        if (oldOrd.ShippedDate == null)
           cmd.Parameters.AddWithValue("@OldShippedDate", DBNull.Value);
        else
             cmd.Parameters.AddWithValue("@OldShippedDate", oldOrd.ShippedDate);

        try
        {
            connection.Open();
            int count = cmd.ExecuteNonQuery();
            if (count > 0)
            {
                success = true; // updated
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
        }
        return success;
    }
}

更新发货日期。我想学好这个,但到目前为止,我很挣扎。

标签: c#sql-server

解决方案


推荐阅读