MS SQL 2005 - 使用子查询进行排序失败
这是真实查询的简化版本,用于显示问题。它可以在示例 Adventureworks 数据库上执行:
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]
这效果很好,但我的问题是,如果我向 order by 字段添加排序规则,我会收到一条奇怪的错误消息:
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
错误是:
Msg 207, Level 16, State 1, Line 7
Invalid column name 'Name'.
带有 collate 子句的查询运行良好,如果没有子查询,但我需要它像这样(出于复杂的原因,但请相信我:))。
有谁知道为什么这个查询失败,以及可能的解决方法是什么?这是一个错误吗?
谢谢! 亚当
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SQL Server 不允许您在 order by 子句中通过别名引用列。例如,这不起作用:
但您可以通过重复列定义来修复该问题:
或者使用子查询:
在您的情况下,最好的修复可能是使用子查询:
SQL Server does not allow you to refer to columns by alias in the order by clause. For example, this won't work:
But you can fix that by repeating the column definition:
Or by using a subquery:
In your case, the best fix is probably to use a subquery: