假设我有一个基本查询,就像这样:
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'。那么,如何正确地格式化通配符字符以与查询参数一起使用?任何帮助都将不胜感激!
DELETE FROM users WHERE userName LIKE '%' + @var + '%'
这样的语句仍然存在很大危险... (实际上,在使用用户输入时,需要过于信任每个人,尤其是在更新语句中使用LIKE
可能会遭到应有的报应 :)) - Alexei Levenkov