查询执行

发布于 2024-11-05 03:00:18 字数 407 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

第几種人 2024-11-12 03:00:18

对于查询 1,您无法按照您尝试执行的方式动态指定要排序的列。但是,您可以构建一个 sql 字符串并使用 EXEC 执行它:

declare @OrderBy varchar(100) = 'CompanyName'
declare @SortingOrder varchar(5) = 'desc'
declare @sql varchar(1000)
SET @sql = 'Select * from [User] order by ' + @OrderBy + ' ' + @SortingOrder
EXEC(@sql)

或者如果您想避免动态 SQL,您可以在 ORDER BY 中使用 CASE WHEN 语句:

declare @OrderBy varchar(100) = 'CompanyName'
declare @so varchar(5) = 'desc'

SELECT * FROM [User] 
ORDER BY
  CASE WHEN @OrderBy = 'CompanyName' AND @so = 'desc' THEN CompanyName END DESC,
  CASE WHEN @OrderBy = 'CompanyName' AND @so <> 'desc' THEN CompanyName END

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:

declare @OrderBy varchar(100) = 'CompanyName'
declare @SortingOrder varchar(5) = 'desc'
declare @sql varchar(1000)
SET @sql = 'Select * from [User] order by ' + @OrderBy + ' ' + @SortingOrder
EXEC(@sql)

Or if you want to avoid dynamic SQL, you can use a CASE WHEN statement in your ORDER BY:

declare @OrderBy varchar(100) = 'CompanyName'
declare @so varchar(5) = 'desc'

SELECT * FROM [User] 
ORDER BY
  CASE WHEN @OrderBy = 'CompanyName' AND @so = 'desc' THEN CompanyName END DESC,
  CASE WHEN @OrderBy = 'CompanyName' AND @so <> 'desc' THEN CompanyName END
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文