2014年6月16日 星期一

MS-SQL 欄位值 大小寫識別 T-SQL

最近發現 MS-SQL 字串欄位,大寫 和 小寫 會視為相同的值,資料比對誤判
只要在欄位名稱後 加上 Collate SQL_Latin1_General_CP1_CS_AS 大小就視為不同,
相反 SQL_Latin1_General_CP1_CI_AS 就視為相同

如下案例:
select
case when  'ABC' = 'abc'   then 'Yes' else 'NO' End  NO_CS_AS ,
case when  'ABC' Collate SQL_Latin1_General_CP1_CS_AS
         = 'abc' then 'Yes' else 'NO' End   CS_AS,
case when  'ABC' Collate SQL_Latin1_General_CP1_CI_AS
         = 'abc' then 'Yes' else 'NO' End   CI_AS

select
case when 'Abc'  = 'ABC'   then '字串模糊比對' else 'Abc <> ABC' end AS "資料庫預設",
case when 'Abc' Collate SQL_Latin1_General_CP1_CS_AS = 'ABC' Collate SQL_Latin1_General_CP1_CS_AS  then '字串大小寫比對' else 'Abc <> ABC' end AS "指定大小寫比對",
case when 'Abc' Collate SQL_Latin1_General_CP1_CI_AS = 'ABC' Collate SQL_Latin1_General_CP1_CI_AS  then '字串模糊比對' else 'Abc <> ABC' end as "指定模糊比對"

參考 http://technet.microsoft.com/zh-tw/library/ms180175(v=SQL.105).aspx