Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 901
Rajakrishnan Avatar asked Oct 19 '15 12:10

Rajakrishnan


2 Answers

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
like image 173
DavidG Avatar answered Sep 19 '22 03:09

DavidG


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.

like image 24
Gordon Linoff Avatar answered Sep 19 '22 03:09

Gordon Linoff