DEV Community

Jennifer Fadriquela
Jennifer Fadriquela

Posted on

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.

Top comments (0)