gpt4 book ai didi

c# - 转义转义符不起作用——SQL LIKE 运算符

转载 作者:太空狗 更新时间:2023-10-30 00:11:17 24 4
gpt4 key购买 nike

我使用 \ 作为 LIKE 运算符的 escape character。我正在转义以下四个字符

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;
}

引用:

  1. How can I escape square brackets in a LIKE clause?
  2. How to escape a string for use with the LIKE operator in SQL Server?

最佳答案

像这样修改您的CustomFormat 方法:

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 LIKE 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13861004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com