SQL 分页查询存储过程中order by 后面不能传变量的问题怎么解决

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL 分页查询存储过程中order by 后面不能传变量的问题怎么解决相关的知识,希望对你有一定的参考价值。

SQL 分页查询存储过程中order by 后面不能传变量的问题怎么解决
我具体sql如下
@orderBy:排序字段
@orderType:排序顺序

select top @pageSize * from
(select f.*,h.Name as LastUserName from
(select a.*,b.TypeName ,c.Name from News a,NewsType b,Users c where a.typeId=b.typeId and a.UserId=c.UserId and a.typeId=@typeId and a.Title like @like )as f , Users as h where f.lastEditUserId =h.userId ) as e
where e.NewsId not in (select top (@pageSize * @pageIndex) a. NewsId from news a,NewsType b, users c where a.typeId=b.typeId and a.UserId=c.UserId and a.Title like @like order by a.@orderBy @orderType) order by e.@orderBy @orderType

一:用exec
二:数据库不排序,交给程序去排序。数据库排序也是需要消耗时间和资源的....而数据库通常是最宝贵的资源。
参考技术A 写成动态sql

以上是关于SQL 分页查询存储过程中order by 后面不能传变量的问题怎么解决的主要内容,如果未能解决你的问题,请参考以下文章

sql子查询 order by失效问题

我可以在不使用 ROW_NUM () OVER (ORDER BY xxxxx) 的情况下在 Sql Server 中对查询进行分页吗?

php sql语句拼接怎么加最后一个分页条件order by id desc LIMIT $pageNum,$numPerPage

Oracle在查询Sql中不使用order by,导致数据量足够大的时候同样的sql查询的结果顺序不同?

Sql Server 按偏移量分页行 - 没有'ORDER BY'

坑,MySQL中 order by 与 limit 混用,分页有BUG!