查询执行
1)
declare @OrderBy varchar(100) = 'CompanyName'
declare @SortingOrder varchar(5) = 'desc'
Select * from [User] order by (@OrderBy + ' ' + @SortingOrder)
2)
Select * from [User] order by CompanyName desc
如果我使用第二个查询,那么结果为真(如我预期),但如果我使用第一个查询,那么结果不符合预期。
我的意思是,结果集是通过按公司名称降序排列来显示的。
第一个查询有什么问题? 有人请解释一下这一点。
谢谢。
1)
declare @OrderBy varchar(100) = 'CompanyName'
declare @SortingOrder varchar(5) = 'desc'
Select * from [User] order by (@OrderBy + ' ' + @SortingOrder)
2)
Select * from [User] order by CompanyName desc
If I use the 2nd query then the result comes true (as I expected), but if I use the 1st query then result is not as expected.
I mean that the result set is displayed by ordering the company name in descending order.
What is the wrong in 1st query?
Someone please explain this.
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于查询 1,您无法按照您尝试执行的方式动态指定要排序的列。但是,您可以构建一个 sql 字符串并使用 EXEC 执行它:
或者如果您想避免动态 SQL,您可以在 ORDER BY 中使用 CASE WHEN 语句:
For query number 1, you can't specify the column you want to order by dynamically the way you're trying to do it. You could however build a sql string and execute it using EXEC:
Or if you want to avoid dynamic SQL, you can use a CASE WHEN statement in your ORDER BY: