如何在带有参数的SQL查询中使用通配符

时间:2013-11-01 16:23:40

标签: c# sql

说我有一个基本的查询,如下所示:

 SELECT holiday_name
 FROM holiday
 WHERE holiday_name LIKE %Hallow%

这在我的sql查询窗格中执行正常并返回'Halloween'。当我尝试在我的代码中使用带有通配符'%'字符的参数时,会出现问题。

SqlConnection Connection = null;
SqlCommand Command = null;

string ConnectionString = ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString;
string CommandText = "SELECT holiday_name "
                   + "FROM holiday "
                   + "WHERE holiday_name LIKE %@name%";
Connection = new SqlConnection(ConnectionString);

try
{
      Connection.Open();
      Command = new SqlCommand(CommandText, Connection);
      Command.Parameters.Add(new SqlParameter("name", HolidayTextBox.Text));
      var results = Command.ExecuteScalar();
}

catch (Exception ex)
{   
     //error stuff here       
}

finally
{
    Command.Dispose();
    Connection.Close();
}

这会引发错误的语法错误。我已经尝试将'%'移动到我的参数中,如此

Command.Parameters.Add(new SqlParameter("%name%", HolidayTextBox.Text));

然后我收到一条错误,说我没有声明标量变量'@name'。那么,如何正确格式化通配符以包含在查询参数中?任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:23)

首先,您的SqlParameter名称为@name而不是name

其次,我会移动你的通配符。

所以它看起来像这样:

string CommandText = "SELECT holiday_name "
               + "FROM holiday "
               + "WHERE holiday_name LIKE @name;"
Connection = new SqlConnection(ConnectionString);

try
{
  var escapedForLike = HolidatyTextBox.Text; // see note below how to construct 
  string searchTerm = string.Format("%{0}%", escapedForLike);
  Connection.Open();
  Command = new SqlCommand(CommandText, Connection);
  Command.Parameters.Add(new SqlParameter("@name", searchTerm));
  var results = Command.ExecuteScalar();
}

请注意LIKE在传递参数时需要特别小心,您需要转义一些字符Escaping special characters in a SQL LIKE statement using sql parameters

答案 1 :(得分:7)

无论你做什么不要这样做

string CommandText = "SELECT holiday_name "
                   + "FROM holiday "
                   + "WHERE holiday_name LIKE '%'" + HolidayTextBox.Text + "'%'";

因为这将打开你的sql注入,而不是这样做:

Command.Parameters.Add(new SqlParameter("@name", "%" + HolidayTextBox.Text + "%"));

您可能想了解Command.Parameters.AddWithValue,例如:

Command.Parameters.AddWithValue("@name", "%" + HolidayTextBox.Text + "%");

答案 2 :(得分:2)

%应该是搜索字符串的一部分,而不是查询。

string CommandText = "SELECT holiday_name "
                + "FROM holiday "
                + "WHERE holiday_name LIKE @name";
Connection = new SqlConnection(ConnectionString);

try
{
    Connection.Open();
    Command = new SqlCommand(CommandText, Connection);
    string name = "%" + HolidayTextBox.Text + "%";
    Command.Parameters.Add(new SqlParameter("@name", name));