【发布时间】:2012-12-13 13:37:23
【问题描述】:
我已将\ 用作escape character 用于LIKE 运算符。我正在转义以下四个字符
1 % 2 [ 3 ] 4 _
当我将转义字符作为输入传递时,查询不会返回值。我怎样才能让它发挥作用?
数据插入
DECLARE @Text VARCHAR(MAX)
SET @Text = 'Error \\\ \\ C:\toolbox\line 180'
INSERT INTO Account (AccountNumber,AccountType,Duration,ModifiedTime)
VALUES (198,@Text,1,GETDATE())
代码
static void Main(string[] args)
{
string searchValue1 = @"Error \\\ \\ C:\toolbox\line 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;
}
参考:
【问题讨论】:
-
您是否考虑过在 C# 中使用不是特殊字符且不会自然出现在数据或搜索字符串中的转义字符?
-
您的 SQL 语句与您提供的代码示例没有相似之处
-
@BenRobinson 我不明白你的意思。你能解释一下吗?
-
自从我写这篇文章后,您已经更改了您的帖子,但我只是指出数据插入中的 SQL 与您的 DisplayTest 方法中的 SQL 完全不同。现在你试图用该代码解释的内容稍微清楚了。
标签: c# sql sql-server linq ado.net