0

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 myConnection = new SqlConnection(ConnectionString))
        {

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

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

 myCommand.ExecuteNonQuery();

            myConnection.Close();
        }
4
  • If you use @UserId, make sure to pass it in as a parameter. Posting the error message and definition of the Custon_MoneyWork table would help.
    – Andomar
    Aug 28, 2011 at 21:58
  • There is no error, it just not working:) @UserId is ok..
    – RaShe
    Aug 28, 2011 at 22:00
  • question is - how do i plus "somevalue"?
    – RaShe
    Aug 28, 2011 at 22:02
  • @RaShe - The code you posted should have given you an error. The syntax is not valid and it references a non existent parameter. Aug 28, 2011 at 22:16

3 Answers 3

3

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
0
1

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);
1

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.

1
  • 1
    No offense, but maybe you need to learn about such stuff first instead of puzzle programming without understanding what you are actually doing. I mean come on, you already bind a parameter in your code... it's clearly you need to get the basics first. Aug 28, 2011 at 22:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.