且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何转义字符串以与 SQL Server 中的 LIKE 运算符一起使用?

更新时间:2023-02-06 11:04:37

要在字符串中搜索%"作为文字而非通配符,需要将其转义为 [%].

To search for "%" as a literal not wildcard in a string, it needs escaped as [%].

现在,SQL Server 只需要转义 3 个字符:% _ [

Now, SQL Server only need 3 characters escaping: % _ [

因此,创建一个标量 udf 来包装它:

So, create a scalar udf to wrap this:

REPLACE(REPLACE(REPLACE(@myString, '[', '[[]'), '_', '[_]'), '%', '[%]')

由于 SQL 中的模式匹配简单(又名:非常有限),不需要更复杂的...

Because of the simplicity (aka: very limited) pattern matching in SQL, nothing more complex is needed...