mssql排序order by42000报错解决

原文链接:https://blog.csdn.net/wang1qqqq/article/details/122961882

在mssql查询中,如果子查询中使用order by,会出现报错:[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]除非另外还指定了 TOP、OFFSET 或 FOR XML,否则,ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效。
如下语法形式会出现报错:

1
2
3
4
select * from (
    select c_date,count(*) cnt from tablename
    order by c_date
) res

 此时是因为order by 用在了子查询中,所以出现报错。

解决方法①:

如果你的实际应用场景允许把order by用在子查询外,也能达到预期效果,就把order by功能放在外层或最外层,即可解决此问题。

1
2
3
4
select * from (
    select c_date,count(*) cnt from tablename
) res
order by c_date

  

解决方法②:

实际应用时有复杂的sql、子查询必须进行order by的场景,此时搭配top 100 percent(保留100%)进行使用,也可以解决问题

1
2
3
4
select * from (
    select top 100 percent c_date,count(*) cnt from tablename
    order by c_date
) res   

  

 

posted @   yinghualeihenmei  阅读(153)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-03-04 ICSharpCode.SharpZipLib 初级使用
2022-03-04 VS2015没有打包界面,没有Visual Studio Installer
点击右上角即可分享
微信分享提示