参数化查询与%

时间:2012-12-12 18:49:12

标签: c# sql-server-2008 select parameterized

我有一个选择陈述

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

这给我一个“错误”

我试过这个

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

这给了'%'错误......正确的方法是什么

2 个答案:

答案 0 :(得分:7)

您必须在实际参数值中添加%,而不是在查询中添加:

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

例如,如果您在字符串valState中保存了一些值,只需在%中附加AddWithValue

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

答案 1 :(得分:1)

尝试将%放入您要绑定的字符串中

stateStr += "%";

然后绑定stateStr