我可以在数据库更新期间增加一些值吗?

时间:2011-08-28 21:54:27

标签: asp.net sql sql-server database sql-update

我可以这样做吗?

int somevalue=500;
string getUpSql = "UPDATE money FROM bank SET Money= @Money + somevalue WHERE UserId=@UserId";

我正在尝试为点击按钮的帐户加一些钱

    protected void BtnWork_Click(object sender, EventArgs e)
    {
        MembershipUser currentUser = Membership.GetUser();
        Guid currentUserId = (Guid)currentUser.ProviderUserKey;
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string getUpSql = "UPDATE money FROM bank SET Money= @Money + somevalue WHERE UserId=@UserId";
 using (SqlConnection myConnection = new SqlConnection(ConnectionString))
        {

           SqlCommand myCommand = new SqlCommand(getUpSql, myConnection);
 myConnection.Open();

 myCommand.Parameters.AddWithValue("@Money",SqlDbType.Int); 

 myCommand.ExecuteNonQuery();

            myConnection.Close();
        }

3 个答案:

答案 0 :(得分:3)

UPDATE语句将名为Money的列增加一个名为@somevalue的参数中的数量的语法是

UPDATE  bank
SET     Money = Money + @somevalue /* Can use Money += @somevalue if 2008 */
WHERE   UserId = @UserId

答案 1 :(得分:1)

  

UPDATE money FROM bank SET Money= @Money + somevalue WHERE UserId=@UserId

您确定要@Money吗?如果你想增加存储在Money列中的值,你需要像Money = Money + @somevalue一样编写它,你必须将somevalue绑定为参数,而不是Money

答案 2 :(得分:1)

您没有递增值。您将其设置为@Money + somevalue,其中@Money设置为SqlDbType.Int的值。

将您的SQL更改为此...

UPDATE money FROM bank SET Money = Money + @somevalue WHERE UserId = @UserId

...然后像这样设置@somevalue@UserId参数......

int somevalue = ... ;
myCommand.Parameters.AddWithValue("somevalue", somevalue);
TypeOfUserId UserId = ... ;
myCommand.Parameters.AddWithValue("UserId", UserId);