Is the LIKE operator case-sensitive with MSSQL Server?

后端 未结 8 755
清歌不尽
清歌不尽 2020-11-27 14:15

In the documentation about the LIKE operator, nothing is told about the case-sensitivity of it. Is it? How to enable/disable it?

I am querying varchar(n)

8条回答
  •  一向
    一向 (楼主)
    2020-11-27 14:32

    If you want to achieve a case sensitive search without changing the collation of the column / database / server, you can always use the COLLATE clause, e.g.

    USE tempdb;
    GO
    CREATE TABLE dbo.foo(bar VARCHAR(32) COLLATE Latin1_General_CS_AS);
    GO
    INSERT dbo.foo VALUES('John'),('john');
    GO
    SELECT bar FROM dbo.foo 
      WHERE bar LIKE 'j%';
    -- 1 row
    
    SELECT bar FROM dbo.foo 
      WHERE bar COLLATE Latin1_General_CI_AS LIKE 'j%';
    -- 2 rows
    
    GO    
    DROP TABLE dbo.foo;
    

    Works the other way, too, if your column / database / server is case sensitive and you don't want a case sensitive search, e.g.

    USE tempdb;
    GO
    CREATE TABLE dbo.foo(bar VARCHAR(32) COLLATE Latin1_General_CI_AS);
    GO
    INSERT dbo.foo VALUES('John'),('john');
    GO
    SELECT bar FROM dbo.foo 
      WHERE bar LIKE 'j%';
    -- 2 rows
    
    SELECT bar FROM dbo.foo 
      WHERE bar COLLATE Latin1_General_CS_AS LIKE 'j%';
    -- 1 row
    
    GO
    DROP TABLE dbo.foo;
    

提交回复
热议问题