简体   繁体   English

SQL 区分大小写比较

[英]SQL case sensitive compare

I like to know with a CASE statement wether two fields are the same.我想通过 CASE 语句了解两个字段是否相同。

I managed to do it with following query but I wonder if there is a better approach?我设法通过以下查询做到了,但我想知道是否有更好的方法? I just want the '=' to do a case sensitive compare.我只想让“=”进行区分大小写的比较。 I tried with COLLATE but then I need to use a WHERE clause which filters my results, I want all the rows.我尝试使用 COLLATE,但随后我需要使用 WHERE 子句来过滤我的结果,我想要所有行。 And with HASHBYTES it seems overkill especially when I need to combine it with ISNULL使用 HASHBYTES 似乎有些过分,尤其是当我需要将它与 ISNULL 结合使用时

DECLARE @myTable AS TABLE (old varchar(255), new varchar(255));
INSERT INTO @myTable VALUES
    ('test', 'test'),
    ('test', 'TEST'),
    (null, null)


SELECT old, new, 
    CASE WHEN HASHBYTES('SHA2_512', old) = HASHBYTES('SHA2_512', new) THEN 'same' ELSE 'changed' END AS updated,
    CASE WHEN HASHBYTES('SHA2_512', ISNULL(old, '')) = HASHBYTES('SHA2_512', ISNULL(new, '')) THEN 'same' ELSE 'changed' END AS updated_isnull
FROM @myTable
--where old = new COLLATE Latin1_General_CS_AS

I need column 'updated_isnull'我需要列 'updated_isnull'

| old  | new  | updated | updated_isnull |
| ---- | ---- | ------- | -------------- |
| test | test | same    | same           |
| test | TEST | changed | changed        |
| NULL | NULL | changed | same           |

The proper solution would be to fix your columns so your data is stored in a case-sensitive collation.正确的解决方案是修复您的列,以便您的数据存储在区分大小写的排序规则中。 Then you would just do:然后你会这样做:

select old, new,
    case when old = new
             or (old is null and new is null)
         then 1
        else 0 
    end as is_same
from @mytable

Using a case-insensitive collation, we could work around like this使用不区分大小写的排序规则,我们可以像这样解决

select old, new,
    case when old collate Latin1_General_Bin = new collate Latin1_General_Bin 
             or (old is null and new is null)
         then 1
        else 0 
    end as is_same
from @mytable

Demo on DB Fiddle : DB Fiddle 演示

old  | new  | is_same
:--- | :--- | ------:
test | test |       1
test | TEST |       0
null | null |       1

Try this:试试这个:

DECLARE @myTable AS TABLE (old varchar(255), new varchar(255));
INSERT INTO @myTable VALUES
    ('test', 'test'),
    ('test', 'TEST'),
    (null, null)


SELECT old, new,
    CASE WHEN old COLLATE Latin1_General_CS_AS = new COLLATE Latin1_General_CS_AS THEN 'same' ELSE 'changed' END AS updated,
    CASE WHEN isnull(old,0) COLLATE Latin1_General_CS_AS = isnull(new,0) COLLATE Latin1_General_CS_AS THEN 'same' ELSE 'changed' END AS updated_isnull
FROM @myTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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