我想知道我的代码在这里缺少什么。我只想从creditrequest表中获取特定值CreditRequest,并将其放在UserData表的creditrequest列中。我的代码以某种方式无法执行任务。

这是我的代码:

using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
    scn.Open();

    SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
    (SELECT CAST(REPLACE(c.CreditRequest, ',', '') as int)
    FROM CreditRequests c Where c.Username=@Username", scn);

    cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = Session["New"];

    cmd.ExecuteNonQuery();
}

最佳答案

让我们逐行查看代码。

using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
//I hope this is correct. Else "Server=PAOLO;Database=ShoppingCartDB;Integrated Security=True"
{
    scn.Open();
/*
    SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
    (SELECT CAST(REPLACE(c.CreditRequest, ',', '') as int)
    FROM CreditRequests c Where c.Username=@Username", scn);
*/
    //SQL statement is all wrong and can update all rows
    //Correct is
    SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest = "
        + "CAST(REPLACE(c.CreditRequest, ',', '') as int) "
        + " FROM CreditRequests c inner join UserData u "
        + "on c.Username=u.Username Where c.Username=@Username", scn);
    cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = (string)Session["New"]; //This is good

    cmd.ExecuteNonQuery();
}

10-07 12:08