如何在SQL Server中使用LIKE运算符找到'%'?

Tej*_* MB 32 t-sql sql-server sql-like

我有一个列名称Address,其中包含一些地址,其中'%'位于:

Address
--------------------
Aman Ja%lan%
Stree% Ro%ad
Run Code Online (Sandbox Code Playgroud)

等等

如何编写LIKE运算符来查找该模式?

我试过了:

declare @var char(1)
set @var='!%'
select Address from Accomodation where Address like '%'+@var+'%'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ith 41

I would use

WHERE columnName LIKE '%[%]%'
Run Code Online (Sandbox Code Playgroud)

SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.

The response to this Connect Item states

We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.

An example

CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)

CREATE NONCLUSTERED INDEX IX ON T(X)

INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT  TOP (100000)  'blah'
FROM master..spt_values v1,  master..spt_values v2


SET STATISTICS IO ON;
SELECT *
FROM T 
WHERE X LIKE '%[%]%'

SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'
Run Code Online (Sandbox Code Playgroud)

显示第一个查询的457个逻辑读取和第二个查询的50,003个逻辑读取.


Joh*_*Woo 19

你可以使用ESCAPE:

WHERE columnName LIKE '%\%%' ESCAPE '\'
Run Code Online (Sandbox Code Playgroud)

  • 使用LIKE'%[%]%'也应该制作技巧. (3认同)