我们常遇到一个存储过程要做都种排序的情况。通常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;
怎么样,感觉不同凡响吧。希望你能有更好的办法。