The problem is simply that string literals / constants and variables (which include parameters) use the current Database's default Collation. When working with a column, the column's Collation is used. Here you are storing the value from a column into a variable, so the Collation of the column no longer matters.
Since you are clearly in a Database that has a case-insensitive default Collation, you need to specify the COLLATE
keyword as part of that comparison. Meaning:
IF ( @andJob LIKE 'y%' COLLATE Latin1_General_CS_AI )
That will override the default behavior of using the Database's Collation for that comparison.
For example:
IF (DB_ID(N'CaseInsensitive') IS NULL)
BEGIN
CREATE DATABASE [CaseInsensitive] COLLATE Latin1_General_100_CI_AS;
ALTER DATABASE [CaseInsensitive] SET RECOVERY SIMPLE;
END;
GO
USE [CaseInsensitive];
SELECT 1 WHERE 'YES' LIKE 'y%';
-- 1
SELECT 2 WHERE 'YES' LIKE 'y%' COLLATE Latin1_General_100_CS_AS;
-- (nothing)
/* -- Clean up:
USE [master];
DROP DATABASE [CaseInsensitive];
*/
Also, you are declaring the variable as varchar(1)
, which seems a bit small. It will truncate any value from szUserdefined6
to just the first character, and I'm not sure that this is the intended behavior.
ALSO, you need to be very careful when doing select @andJob = (SELECT szUserdefined6 from inserted )
in a Trigger. A Trigger that is executed from a multi-row DML operation will have one row per each affected row in the inserted
and/or deleted
tables. What you are doing here only captures the value of the final row in the inserted
table, hence it only truly works if there is NEVER a multi-row INSERT
or UPDATE
against this table.
For more info on collations, encodings, etc, please visit: Collations Info