ASCII与Unicode 两种编码方式对LIKE模糊匹配查找的影响

来源:互联网 发布:你对大数据的理解 编辑:程序博客网 时间:2024/05/18 02:58
 

LIKE 支持 ASCII 模式匹配和 Unicode 模式匹配。当所有参数,包括 match_expression、pattern 和 escape_character(如果有)都是 ASCII 字符数据类型时,将执行 ASCII 模式匹配。如果其中任何参数属于 Unicode 数据类型,则所有参数将被转换为 Unicode 并执行 Unicode 模式匹配。当对 Unicode 数据(nchar 或 nvarchar 数据类型)使用 LIKE 时,尾随空格是有意义的。但是对于非 Unicode 数据,尾随空格没有意义。Unicode LIKE 与 SQL-92 标准兼容。ASCII LIKE 与 SQL Server 的早期版本兼容。

下面的一系列示例显示 ASCII LIKE 模式匹配与 Unicode LIKE 模式匹配所返回的行之间的差异:

-- ASCII pattern matching with char column

CREATE TABLE t (col1 char(30))

INSERT INTO t VALUES ('Robert King')

SELECT *

FROM t

WHERE col1 LIKE '% King'   -- returns 1 row

 

-- Unicode pattern matching with nchar column

CREATE TABLE t (col1 nchar(30))

INSERT INTO t VALUES ('Robert King')

SELECT *

FROM t

WHERE col1 LIKE '% King'   -- no rows returned

 

-- Unicode pattern matching with nchar column and RTRIM  --用rtrim()函数去掉字符串右边的尾随空格

CREATE TABLE t (col1 nchar (30))

INSERT INTO t VALUES ('Robert King')

SELECT *

FROM t

WHERE RTRIM(col1) LIKE '% King'   -- returns 1 row