18.4.11

Increase SQL Value By 1?

Hey,

Fast solution for today.
Ever wanted to increase SQL value by 1 ?
Yes, a stupid way to do it is by using SELECT to read the value, and then use UPDATE to update to the new value. (Your prolly asked your self, why cant i VALUE++?!)

So you can do it in 1 request using UPDATE :)
Ever thought of Value = Value + 1

using (SqlConnection con = new SqlConnection(SQL.ConnectionString())) //Use your own Connection String
{
    con.Open();
    string sqlString = "UPDATE Table SET Value=Value+1 WHERE Condition=@Condition";
    SqlCommand cmd = new SqlCommand(sqlString, con); 
    cmd.Parameters.Add("@Condition", ConditionString); 
    rowAffected = cmd.ExecuteNonQuery(); 
    if (rowAffected > 0) 
        DoSomething(); //Success! 
    else 
        DoSomething(); //Fail!
}

As you see i'm using Parameterized Query that i will explain in a later post.
This code will increase 'Value' by 1 where 'Condition'='ConditionString'. 
connection will automaticly close becuase of the 'using' statement.

Hope it helps you,
Have fun and Happy Passover :P

11.4.11

SQL NOW() wont work in Stored Procedures

Hey everyone im back after long time.. :)

This time i'm gonna give you a little solution to a problem i faced few weeks ago.

Have you ever wondered why 'NOW()' wont work in MSSQL Stored Procedure?
Yes, i wondered too.

So the replacment to 'NOW()' is 'GETDATE()' :)
So just use 'GETDATE()' it will give you the same result as 'NOW()'

Hope this little solution helps you
And i'm back now to give you all more solutions :)