Microsoft SQL Server string compare case sensitive

Table of Contents

Sometimes, your collections of data might contain case sensitive values. In my case, there are several products that have the same Manufacturer but our client misused that data and created duplicated “same” manufacturers without verifying if they exist in the system or not. It leads to an issue that the product might load the incorrect manufacturer every time the application loads its detail. The relationship between product and manufacturer changes too often because of below SQL Script:

/**
* This query returns all products that exists in both 'EERO' and 'eero' manufacturer
**/
DECLARE @ManufacturerName NVARCHAR(255);
SET @ManufacturerName = 'EERO' -- This name is duplicated with 'eero'
SELECT p.* 
FROM products p
INNER JOIN manufacturers m on m.id = p.manufacturer_id
WHERE m.name = @ManufacturerName -- We only need to get which products that have manufacturer of 'EERO' not 'eero'

To fix the issue, we should add `COLLATE Latin1_General_CS_AS ` as below:

DECLARE @ManufacturerName NVARCHAR(255);
SET @ManufacturerName = 'EERO' -- This name is duplicated with 'eero'
SELECT p.* 
FROM products p
INNER JOIN manufacturers m on m.id = p.manufacturer_id
WHERE m.name = @ManufacturerName COLLATE Latin1_General_CS_AS -- case sensitive comparison

That’s it.
Happy coding.