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