I know that you can increment a value in SQL by doing the following:
"UPDATE Table SET value=value 1 where Id=@Id"
Now, I'm wondering if it's possible to do the equivalent with parameters?
I've tried
string sql = "UPDATE Table SET value=@value where Id=@Id"
var cmd = new SQLiteCommand(sql, conn);
cmd.Parameters.Add("@value", DBType.Int).Value = "value 1";
but it didn't work, unsurprisingly. Is there any way to accomplish this with Parameters? If not and I use the first query, is it safe regarding injections?
CodePudding user response:
You can't pass an expression as a parameter, only a value. If you know that you want to increment but you don't know by how much then you can use this SQL:
UPDATE SomeTable SET SomeColumn = SomeColumn @Increment WHERE Id = @Id
and then you can pass 1 to that parameter to increment by 1, etc. Unless you pass all the SQL code in as a string
and tell the database to parse that and execute it as SQL, you have to include all the logic in the SQL code and the parameters can only be data values. It's just how C# works. You couldn't pass part of the logic into a method as a string
and expect it to be executed.