简体   繁体   中英

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.

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

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.

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' ,, ie uppercase

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

thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM