简体   繁体   中英

SQL case sensitive compare

I like to know with a CASE statement wether two fields are the same.

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. And with HASHBYTES it seems overkill especially when I need to combine it with 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'

| 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 :

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

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