利用动态SQL解决排序问题
2024-07-21 02:06:07
供稿:网友
我们常遇到一个存储过程要做都种排序的情况。通常order by 的条件只有一个固定的,这是远远不够的。需要用一个变量来替换它,而oracle有不能识别order by后面的字符串。该怎么办呢?先看看我的一个糟糕方案:
if myorderby='objectid desc' then --按名称排序
open outcur for select * from(
select rownum rowno,t.* from (
select objectid , hits,posttime from cartoon order by objectid desc) t
where rownum<endrow) where rowno>=startrow;
elsif myorderby='hits desc' then --按点击率排序
open outcur for select * from(
select rownum rowno,t.* from (
select objectid , hits,posttime from cartoon order by hits desc') t
where rownum<endrow) where rowno>=startrow;
else --按时间排序
open outcur for select * from(
select rownum rowno,t.* from (
select objectid , hits,posttime from cartoon order by hits desc') t
where rownum<endrow) where rowno>=startrow;
end if;
这虽然是通常使用的两种排序方式得以功过,但显得繁杂而且不够通用。
这时我的同事的好办法:
---------------------------------------------------------------------------
if (myorderby is not null) then
mysql:='select * from( select rownum rowno,t.* from (
select objectid , hits,posttime from cartoon order by '|| myorderby ||
') t where rownum<' || endrow || ') where rowno>=' || startrow;
else
mysql:='select * from( select rownum rowno,t.* from (
select objectid , hits,posttime from cartoon order by posttime desc) t
where rownum<' || endrow || ') where rowno>=' || startrow;
end if;
open outcur for mysql;
怎么样,感觉不同凡响吧。希望你能有更好的办法。