EagleFox
EagleFox

Reputation: 1367

Parameterized query with %

I have a select statement

command.commandText = "SELECT FIRSTNAME, LASTNAME FROM MYTABLE" +
                      " WHERE STATE LIKE @STATE + '%';";

This gives me an "'" error

I tried this one

command.commandText = "SELECT FIRSTNAME, LASTNAME FROM MYTABLE" +
                      " WHERE STATE LIKE @STATE" + "'%';";

This gives me '%' error... What is the correct way

Upvotes: 2

Views: 129

Answers (2)

Nemanja Boric
Nemanja Boric

Reputation: 22157

You must add % in actual parameter value, not in query:

command.commandText = "SELECT FIRSTNAME, LASTNAME FROM MYTABLE WHERE STATE LIKE @STATE";
command.Parameters.AddWithValue("STATE", "CALI%");

If you have some value saved in string valState, for example, just append % in AddWithValue:

string valState = "Cali";
// ...
command.Parameters.AddWithValue("STATE", valState + "%");

Upvotes: 7

Nick Rolando
Nick Rolando

Reputation: 26167

Try putting the % in the string you are binding instead

stateStr += "%";

Then bind stateStr

Upvotes: 1

Related Questions