SQL-Server is ignoring my COLLATION when I'm using LIKE operator

耗尽温柔 提交于 2019-12-22 08:46:11

问题


I'm working with Spanish database so when I'm looking for and "aeiou" I can also get "áéíóú" or "AEIOU" or "ÁÉÍÓÚ", in a where clause like this:

SELECT * FROM myTable WHERE stringData like '%perez%'

I'm expencting:

* perez
* PEREZ
* Pérez
* PÉREZ

So I changed my database to collation: Modern_Spanish_CI_AI

And I get only:

* perez
* PEREZ

But if I do:

SELECT * FROM myTable WHERE stringData like '%perez%' COLLATE Modern_Spanish_CI_AI 

I get all results OK, so my question is, why if my database is COLLATE Modern_Spanish_CI_AI I have to set the same collation to my query???

I'm using SQL-Server 2008


回答1:


You need to change the collation of the table COLUMN itself.

select collation_name, *
from sys.columns
where object_id = object_id('tblname')
  and name = 'stringdata';

If you're lucky it is as easy as (example)

alter table tblname alter column stringdata varchar(20) collate Modern_Spanish_CI_AS

But if you have constraints and/or schema bound references, it can get complicated.
It can be very difficult to work with a database with mixed collations, so you may want to re-collate all the table columns.




回答2:


You can use COLLATE, eg.

SELECT * 
FROM TableName
WHERE strData COLLATE Latin1_general_CI_AI = 'perez' COLLATE Latin1_general_CI_AI

both sides must have the same collation.

  • SQLFiddle Demo
  • SQLFiddle Demo (using LIKE)

Others:

  • Selecting a SQL Server Collation


来源:https://stackoverflow.com/questions/16660346/sql-server-is-ignoring-my-collation-when-im-using-like-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!