2016-06-01 67 views
2

我想知道我在代碼中丟失了什麼。我想要發生的一切是從,從CreditRequest表中獲取特定值,並將其放入UserData表中,creditrequest列。不知何故,我的代碼沒有執行任務。更新SQL語句不會觸發數據庫

這裏是我的代碼:

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 [email protected]", scn); 

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

    cmd.ExecuteNonQuery(); 
} 
+0

爲什麼你有兩個陳述。嘗試刪除下一個'SELECT',然後使用'ExecuteNonQuery'來代替。 –

+0

嘗試刪除第二條語句(忘記刪除它)並將其更改爲executenonquery。仍然不工作@FelixPamittan –

+0

fyi,我在我的其他按鈕中有相同的代碼,並且工作得很好。不知道爲什麼這一個不工作 –

回答

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 [email protected]", 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 [email protected]", scn); 
    cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = (string)Session["New"]; //This is good 

    cmd.ExecuteNonQuery(); 
} 
+0

非常感謝! :) –