Search code examples
c#sql-server-2008selectparameterized

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


Solution

  • 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 + "%");