Escape SQL LIKE wildcard characters

jengfad

Jennifer Fadriquela

Posted on June 26, 2020

Escape SQL LIKE wildcard characters

In MSSQL, LIKE operator has wildcard characters that aids in pattern matching.

If you want to disable it, one way is to manually escape it. In my case, I made a string extension to transform the search text before passing it to the stored procedure via ADO.

SQL recognizes which character to escape if it was enclosed in [] with the exemption of single quote '.

public static string EscapeSqlChars(this string input)
{
    return input
        .Replace(@"[", @"[[]")
        .Replace(@"\", @"[\]")
        .Replace(@"'", @"''")
        .Replace(@"%", @"[%]")
        .Replace(@"_", @"[_]");
}
Enter fullscreen mode Exit fullscreen mode

Read more discussions here.

💖 💪 🙅 🚩
jengfad
Jennifer Fadriquela

Posted on June 26, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related