Sample Header Ad - 728x90

Collation conflict when comparing sql_variant with varchar literal

8 votes
2 answers
1140 views
I found that queries below return different results on two Azure Hyperscale databases that are running the same compatibility level, same set options etc.
IF CAST(ServerProperty('Edition') AS nvarchar(128)) = 'SQL Azure' BEGIN
	SELECT 1
END
IF ServerProperty('Edition') = 'SQL Azure' BEGIN
	SELECT 2
END
IF 'SQL Azure' = ServerProperty('Edition') BEGIN
	SELECT 3
END
On one database, it returns only 1, on other database it returns 1,2 and 3. I investigated the root cause and it seems to be caused by different collations of the databases. For following queries:
SELECT SQL_VARIANT_PROPERTY(ServerProperty('Edition'), 'Collation')
SELECT name, collation_name, compatibility_level FROM sys.databases
The database which returns only one row, the result is:
-----------------------------
SQL_Latin1_General_CP1_CI_AS

name         collation_name                   compatibility_level
------------ -------------------------------- -------------------
master       SQL_Latin1_General_CP1_CI_AS     140
my_database  SQL_Latin1_General_CP850_CI_AS   150
And the result from database that returns 1,2,3 is:
-----------------------------
SQL_Latin1_General_CP1_CI_AS

name         collation_name                   compatibility_level
------------ -------------------------------- -------------------
master       SQL_Latin1_General_CP1_CI_AS     140
my_database  SQL_Latin1_General_CP1_CI_AS     150
So the simple comparison without the cast is comparing sql_variant with varchar (there is no difference when I use N'SQL Azure') where the underlying nvarchar from the sql_variant has in one case different collation than the DB I query and in other case it's matching. First of all, I would assume the comparison of two strings with different collation would fail like it fails when you try to join on two columns with different collation, but it's apparently not the case here. Anyway, what's the best way to safely compare output of a function that might be sql_variant with a varchar?
Asked by Lukas.Navratil (355 rep)
Oct 7, 2022, 09:20 AM
Last activity: Oct 8, 2022, 07:30 AM