Can I increment some value during database update?
Can i do something like that?
int somevalue=500;
string getUpSql = "UPDATE money FROM bank SET Money= @Money + somevalue WHERE UserId=@UserId";
I'm trying to plus some money to an account that clicks button
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 my开发者_运维问答Connection = new SqlConnection(ConnectionString))
{
SqlCommand myCommand = new SqlCommand(getUpSql, myConnection);
myConnection.Open();
myCommand.Parameters.AddWithValue("@Money",SqlDbType.Int);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
The syntax for an UPDATE
statement to increment a column called Money
by the amount in a parameter called @somevalue
is
UPDATE bank
SET Money = Money + @somevalue /* Can use Money += @somevalue if 2008 */
WHERE UserId = @UserId
You are not incrementing the value. You are setting it to @Money + somevalue
, where @Money
is set to whatever the value of SqlDbType.Int
is.
Change your SQL to this...
UPDATE money FROM bank SET Money = Money + @somevalue WHERE UserId = @UserId
...and then set the @somevalue
and @UserId
parameters like this...
int somevalue = ... ;
myCommand.Parameters.AddWithValue("somevalue", somevalue);
TypeOfUserId UserId = ... ;
myCommand.Parameters.AddWithValue("UserId", UserId);
UPDATE money FROM bank SET Money= @Money + somevalue WHERE UserId=@UserId
Are you sure you want @Money
? If you want to increment the value stored in the column Money by somevalue you need to write it like Money = Money + @somevalue
and you have to bind somevalue as a parameter, not Money
.
精彩评论