I have used
as escape character
for LIKE
operator. I am escaping following four characters
1 %
2 [
3 ]
4 _
When I pass the escape character as input, the query does not return a value. How can I make it work?
Data Insert
DECLARE @Text VARCHAR(MAX)
SET @Text = 'Error \ \ C:oolboxline 180'
INSERT INTO Account (AccountNumber,AccountType,Duration,ModifiedTime)
VALUES (198,@Text,1,GETDATE())
CODE
static void Main(string[] args)
{
string searchValue1 = @"Error \ \ C:oolboxline 180";
string searchValue2 = @"55555";
string result1 = DisplayTest(searchValue1);
string result2 = DisplayTest(searchValue2);
Console.WriteLine("result1:: " + result1);
Console.WriteLine("result2:: " + result2);
Console.ReadLine();
}}
private static string DisplayTest(string searchValue)
{
searchValue = CustomFormat(searchValue);
string test = String.Empty;
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = @"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE @input ESCAPE ''";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("@input", "%" + searchValue + "%");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
test = reader.GetString(0);
}
}
}
}
}
return test;
}
private static string CustomFormat(string input)
{
input = input.Replace(@"%", @"\%");
input = input.Replace(@"[", @"[");
input = input.Replace(@"]", @"]");
input = input.Replace(@"_", @"\_");
//input = input.Replace(@"", @"");
return input;
}
REFERENCE:
- How can I escape square brackets in a LIKE clause?
- How to escape a string for use with the LIKE operator in SQL Server?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…