This is a simplified version of a real query to show the problem. It can be executed on the sample Adventureworks database:
SELECT Person.Address.*,
(SELECT TOP 1 [Name]
FROM Person.StateProvince
WHERE Person.StateProvince.StateProvinceId = Person.Address.StateProvinceId AND Person.StateProvince.TerritoryId IN (5, 6, 7)
ORDER BY Person.StateProvince.TerritoryId) AS [Name]
FROM Person.Address
ORDER BY [Name]
This works well, but my problem is that if I add collation to the order by field, I get a strange error message:
SELECT Person.Address.*,
(SELECT TOP 1 [Name]
FROM Person.StateProvince
WHERE Person.StateProvince.StateProvinceId = Person.Address.StateProvinceId AND Person.StateProvince.TerritoryId IN (5, 6, 7)
ORDER BY Person.StateProvince.TerritoryId) AS [Name]
FROM Person.Address
ORDER BY [Name] COLLATE Chinese_PRC_CI_AI
And the error is:
Msg 207, Level 16, State 1, Line 7
Invalid column name 'Name'.
The query with the collate clause works well if there's no subquery, but I need it to be like this (for a complicated reason, but please believe me :)).
Does anybody know why this query fails, and what can be a possible workaround? Is this a bug?
Thanks! Adam