UPDATE
Following four characters need to be escaped when '\' is the escape helper %[]_
- http://msdn.microsoft.com/en-us/library/aa933232(v=sql.80).aspx - LIKE
- Escape a string in SQL Server so that it is safe to use in LIKE expression
- How do I escape _ in SQL Server?
QUESTION
Though I searched a lot, I could not find out a problem exactly matching the following, in stack overflow.
I have a database column called Log_Description. It has two records.
1) "Sample % value record"
2) "Sample free record"
I am using SQL Command and setting parameters as shown below
commandText = commandText + “Log_Description LIKE @Log_Description”;
command.Parameters.AddwithValue(“@Log_Description”, “%”+obj. LogDescription+”%”);
Suppose the user enters “%” as search param for txtLogDescription textbox, I need to show only first record. But currently it is showing both the records.
- What are the possible ways to overcome this?
- What are the other characters that may cause such issues with the above code?
Note: I cannot prevent user from entering “%” as input
Note: I am using SQL Server as database
EDIT:
Solution I am using now is 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 approach (with performance hit) is below
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;
}