我正在尝试编写一个 PL/SQL 过程,它将使用 SQL 查询来获取结果。但是要求是order by可以是动态的,主要是对屏幕中的列进行排序。我将 2 个参数传递给此过程 - in_sort_column 和 in_sort_order。 要求是在文本列上排序是 ASC,对于数字是 DESC。 我的查询看起来像这样,没有添加 in_sort_order -
SELECT col1, col2, col3 from tabl e1 where col1 > 1000
ORDER BY decode(in_sort_column,'col1', col1, 'col2', col2, 'col3', col3);
在这种情况下,我不知道如何使用 in_sort_order 参数。以前做过这件事的人可以帮忙吗?
谢谢
最佳答案
在进行动态排序时,我建议使用separate 子句:
order by (case when in_sort_column = 'col1' then col1 end),
(case when in_sort_column = 'col2' then col2 end),
(case when in_sort_column = 'col3' then col3 end)
如果列的类型不同,这可以保证您不会遇到类型转换的意外问题。请注意,case
返回 NULL
而没有 else
子句。
关于sql - 如何在 PL/SQL 程序中生成动态 Order by 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29043672/