Comparing the same character in VARCHAR and NVARCHAR differs between CP1/CP1252 vs. CP850 based on DB collation

Viewed 5483

Here are my two variables:

DECLARE @First VARCHAR(254) = '5’-Phosphate Analogs Freedom to Operate'
DECLARE @Second NVARCHAR(254) = CONVERT(NVARCHAR(254), @First)

I have two databases, let's call them "Database1" and "Database2". Database1 has a default collation of SQL_Latin1_General_CP850_CI_AS; Database2 is SQL_Latin1_General_CP1_CI_AS. Both databases have a compatibility level of SQL Server 2008 (100).

I first connect to Database1 and run the following queries:

SELECT CASE 
    WHEN @First COLLATE SQL_Latin1_General_CP1_CI_AS 
    = @Second COLLATE SQL_Latin1_General_CP1_CI_AS 
    THEN 'Equal' ELSE 'Not Equal' END

SELECT CASE 
    WHEN @First COLLATE SQL_Latin1_General_CP850_CI_AS 
    = @Second COLLATE SQL_Latin1_General_CP850_CI_AS 
    THEN 'Equal' ELSE 'Not Equal' END

The results are:

Equal
Equal

Then I connect to Database2 and run the queries; the results are:

Equal
Not Equal

Note that I have not changed the queries themselves, just the db connection, and I'm specifying the collations to be used rather than allowing them to use the databases' default collations. Therefore, it's my understanding that the database default collation should not matter, i.e. the results of the queries should be the same regardless of which database I'm connected to.

I have three questions:

  1. Why do I get different results when the only thing I change is the database to which I'm connected, given that I've effectively ignored the default database collation by explicitly specifying my own?

  2. For the test against Database 2, why does the comparison succeed with the SQL_Latin1_General_CP1_CI_AS collation and fail with the SQL_Latin1_General_CP850_CI_AS collation? What is the difference between the two collations that account for this?

  3. Most Perplexing: If the default collation of the database to which I'm connected does matter, as it would seem, and the default collation of Database1 is SQL_Latin1_General_CP850_CI_AS (which, remember from my first test resulted in Equal, Equal) why does the second query, which explicitly specifies the very same collation fail (Not Equal) when connected to Database2?

1 Answers
Related