quot;Order Byquot; using a parameter for the column name(“订购者使用列名参数)
问题描述
我们希望在使用 Visual Studio 数据集设计器创建的查询或存储过程的Order By"子句中使用参数.
We would like to use a parameter in the "Order By" clause of a query or stored procedure created with the Visual Studio DataSet Designer.
示例:
FROM TableName
WHERE (Forename LIKE '%' + @SearchValue + '%') OR
(Surname LIKE '%' + @SearchValue + '%') OR
(@SearchValue = 'ALL')
ORDER BY @OrderByColumn
显示此错误:
Variables are only allowed when ordering by an expression referencing
a column name.
推荐答案
你应该能够做这样的事情:
You should be able to do something like this:
SELECT *
FROM
TableName
WHERE
(Forename LIKE '%' + @SearchValue + '%') OR
(Surname LIKE '%' + @SearchValue + '%') OR
(@SearchValue = 'ALL')
ORDER BY
CASE @OrderByColumn
WHEN 1 THEN Forename
WHEN 2 THEN Surname
END;
- 将 1 分配给
@OrderByColumn以对Forename进行排序. - 分配 2 以对
Surname进行排序. - 等等……您可以将此方案扩展到任意数量的列.
- Assign 1 to
@OrderByColumnto sort onForename. - Assign 2 to sort on
Surname. - Etc... you can expand this scheme to arbitrary number of columns.
不过要注意性能.这些类型的构造可能会干扰查询优化器找到最佳执行计划的能力.例如,即使 Forename 被索引覆盖,查询可能仍然需要完整排序,而不是仅仅按顺序遍历索引.
Be careful about performance though. These kinds of constructs may interfere with query optimizer's ability to find an optimal execution plan. For example, even if Forename is covered by index, query may still require the full sort instead of just traversing the index in order.
如果是这种情况,并且您无法忍受性能影响,则可能需要为每个可能的排序顺序使用单独的查询版本,从而使客户端的事情变得相当复杂.
If that is the case, and you can't live with the performance implications, it may be necessary to have a separate version of the query for each possible sort order, complicating things considerably client-side.
这篇关于“订购者"使用列名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“订购者"使用列名参数
基础教程推荐
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 在多列上分布任意行 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- oracle区分大小写的原因? 2021-01-01
