I am working on a windows form application. I want to change the SQL command by user selection. Here is my code:
command.CommandText = "SELECT * FROM Product WHERE price = @price";
command.Parameters.AddWithValue("@price", 35);
I also want to change "=" to ">=" or something else. When I use parameters for that, I get errors.
command.CommandText = "SELECT * FROM Urun WHERE price @equal @price";
command.Parameters.AddWithValue("@price", 35);
command.Parameters.AddWithValue("@equal", ">=");
How can I do that?
You can't, basically. Parameterized SQL is just for values - not table names, column names, or operators. This is one place where you do probably want to build the SQL dynamically - but with a white-listed set of options.
Whether you build the full SQL up dynamically from bits, or whether you have a set of pre-canned complete SQL queries, will depend on exactly what you're trying to do. And obviously you should still use parameters for the values.
See more on this question at Stackoverflow