Perform a Case insensitive Like query in a case sensitive SQL Server database

混江龙づ霸主 提交于 2021-02-07 13:38:55

问题


This is my scenario.

SQL Server 2014 Standard edition, I have a database with a collation SQL_Latin1_General_CP437_BIN2 which is case sensitive.

I want to perform a LIKE query which should return the output irrespective of case sensitive.

Ex: if i execute a Like query to fetch the records with userName 'John' it should also return rows irrespective of case sensitive 'JOHN', 'John', 'john','joHN'.

I tried using Lcase, Ucase, but I am getting the error

Msg 195, Level 15, State 10, Line 4
'LCASE' is not a recognized built-in function name.

This is my sample query

SELECT TOP 300 * 
FROM
    (SELECT 
         userNo, userName, Place, Birthdate
     FROM usertable 
     WHERE personid = 2 
       AND (Name LIKE LCASE('%john%')) 

     UNION 

     SELECT 
         userNo, userName, Place, Birthdate, 
     FROM usertable2 
     WHERE personid = 2 
       AND (Name LIKE LCASE( '%john%') OR Place LIKE LCASE('%NY%')) ) a 
ORDER BY 
    userNo

Guys help me out with your valuable suggestions , I am bit confused of using collation based DB.


回答1:


You can use UPPER or LOWER functions to convert the values to the same case. For example:

SELECT *
FROM YourTable
WHERE UPPER(YourColumn) = UPPER('VALUE')

Alternatively, you can specify the collation manually when comparing:

SELECT *
FROM YourTable
WHERE YourColumn = 'VALUE' COLLATE SQL_Latin1_General_CP1_CI_AI



回答2:


In addition to using lower(), you need to apply it to the column not the pattern. The pattern is already lower case.

Select  top 300 a.*
from (SELECT userNo, userName, Place, Birthdate
      FROM usertable 
      where personid = 2 and lower(Name) LIKE '%john%'
      UNION 
      SELECT userNo, userName, Place, Birthdate
      FROM usertable2 
      where personid = 2 and
            (lower(Name) like '%john%' or lower(Place) like '%ny%')
     ) a
order by userNo;

Note that UNION ALL is preferable to UNION, unless you intentionally want to incur the overhead of removing duplicates.




回答3:


The Syntax Is differ Over Different Db-Provider For Example:

select * from TABLE1 where upper(COL) like 'SOMETHING',, gives syntax error in ODCB Provider for Microsoft... and the right syntax is : select * from TABLE1 where ucase(COL) like 'SOMETHING' ,, i.e. uppercase

So you should use the correct syntax used by your db provider

thanks




回答4:


use code below

SELECT TOP 300 * FROM (SELECT userNo, userName, Place, Birthdate FROM usertable WHERE personid = 2 AND (Name LIKE '%john%') UNION

 SELECT 
     userNo, userName, Place, Birthdate, 
 FROM usertable2 
 WHERE personid = 2 
   AND (Name LIKE '%john%' OR Place LIKE '%NY%') a 

ORDER BY userNo



来源:https://stackoverflow.com/questions/33213945/perform-a-case-insensitive-like-query-in-a-case-sensitive-sql-server-database

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