[SQL SERVER][Memo]LIKE statement

[SQL SERVER][Memo]LIKE statement

我在論壇上看到網友詢問LIKE相關問題,相信大家都會使用Like來搜尋資料,

所以我也不多說相關用法,這裡我筆記一下Like所支援的兩種比對模式(Ascii 和 Unicode),

順便也加強自己的印象。

 

先來看看線上叢書的說明

image

框選的文字簡單來說如下:

當你使用LIKE來搜尋Unicode資料時,尾端空白是有意義的。

當你使用LIKE來搜尋非Unicode資料時,尾端空白是沒有意義的。

 

下面就來實際測試兩種模式差異

create table mytest1
(c1 int identity(1,1) not null,
c2 char(10) null,
c3 nchar(10) null
);

	
insert into mytest1
select 'rico123 ',null union all --c2尾端空白 資料長度8
select null,'rico123 ' union all --c3尾端空白 資料長度8
select ' rico123',null union all --c2開頭空白 資料長度8
select null,' rico123' union all --c3開頭空白 資料長度8
select ' rico123 ',null union all --c2開頭和尾端空白  資料長度9
select null,' rico123 '           --c3開頭和尾端空白 資料長度9

 

ASCII模式

image
由於 C2 是 非Unicode 資料,所以採用 ASCII 模式比對,
當我在查詢rico開頭資料時,尾端空白沒有意義(不重要),
但開頭空白是有意義的喔,所以SQL Server只回傳1筆資料給我.
 
當我在在查詢3結尾時,SQL Server回傳3筆資料給我(因為尾端空白沒有意義)
 
Unicode模式
image
由於 C3 是 Unicode 資料,所以採用 Unicode 模式比對,
當我在查詢rico開頭資料時,尾端空白有意義(很重要),
所以SQL Server只回傳1筆資料給我.
 
當我在在查詢3結尾時,SQL Server回傳0筆資料給我(因為尾端空白有意義)
 

最後再次強調,當你使用Like再搜尋Unicode資料時,尾端空白是很重要的喔

 

參考

LIKE (Transact-SQL)