利用动态SQL解决排序问题
2024-07-21 02:39:43
供稿:网友
我们常碰到一个存储过程要做都种排序的情况。通常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;怎么样,感觉不同凡响吧。希望你能有更好的办法。