【发布时间】:2012-11-15 07:06:34
【问题描述】:
更新
当'\'为转义助手%[]_时,后面四个字符需要转义
- http://msdn.microsoft.com/en-us/library/aa933232(v=sql.80).aspx - 喜欢
- Escape a string in SQL Server so that it is safe to use in LIKE expression
- How do I escape _ in SQL Server?
问题
虽然我搜索了很多,但在堆栈溢出中我找不到与以下完全匹配的问题。
我有一个名为 Log_Description 的数据库列。它有两条记录。
1)“样本百分比值记录”
2) “样品免费记录”
我正在使用SQL命令并设置参数如下所示
commandText = commandText + “Log_Description LIKE @Log_Description”;
command.Parameters.AddwithValue(“@Log_Description”, “%”+obj. LogDescription+”%”);
假设用户输入“%”作为 txtLogDescription 文本框的搜索参数,我只需要显示第一条记录。但目前它正在显示这两个记录。
- 有哪些可能的方法来克服这个问题?
- 还有哪些其他字符可能会导致上述代码出现此类问题?
注意:我无法阻止用户输入“%”作为输入
注意:我使用 SQL Server 作为数据库
编辑:
我现在使用的解决方案是Escaping the escape character does not work – SQL LIKE Operator
private static string CustomFormat(string input)
{
input = input.Replace(@"\", @"\\");
input = input.Replace(@"%", @"\%");
input = input.Replace(@"[", @"\[");
input = input.Replace(@"]", @"\]");
input = input.Replace(@"_", @"\_");
return input;
}
LINQ 方法(性能受到影响)如下
Collection<Log> resultLogs = null;
if (!String.IsNullOrEmpty(logSearch.LogDescription))
{
resultLogs = new Collection<Log>();
var results = from o in logs where o.LogDescription.Contains(logSearch.LogDescription) select o;
if (results != null)
{
foreach (var log in results)
{
resultLogs.Add((Log) log);
}
}
}
else
{
resultLogs = logs;
}
【问题讨论】:
-
你用的是什么数据库? SQL Server、甲骨文、MySQL?
-
如果您使用的是 SQL Server,这里有一个类似的问题 stackoverflow.com/a/258947/1045728 ,基本上您会转义在搜索值中找到的任何 %
标签: c# .net sql-server linq ado.net