更新未向数据库触发的SQL语句

时间:2016-06-01 02:14:30

标签: c# asp.net sql-server sql-update

我想知道我的代码中缺少什么。我想要的是从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();
}

1 个答案:

答案 0 :(得分:0)

让我们逐行查看代码。

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();
}