我有pl / sql的循环脚本,我的脚本由i asc返回,
DECLARE
i NUMBER;
BEGIN
FOR rec IN (
SELECT 1 as i from dual
UNION
SELECT 2 as i from dual
UNION
SELECT 3 as i from dual
UNION
SELECT 4 as i from dual
)
LOOP
DBMS_OUTPUT.PUT_LINE (rec.i);
END LOOP;
end;
然后它返回
1
2
3
4
但我需要订购
1
4
3
2
我应该用什么功能来解决问题,谢谢advence
答案 0 :(得分:1)
我希望这可以归还你想要的东西:
DECLARE
i NUMBER;
BEGIN
FOR rec IN (
SELECT 1 as i from dual
UNION ALL
SELECT 4 as i from dual
UNION ALL
SELECT 3 as i from dual
UNION ALL
SELECT 2 as i from dual
) LOOP
DBMS_OUTPUT.PUT_LINE (rec.i);
END LOOP;
end;
然而,这仅仅是因为数据很小。 Oracle不保证在没有ORDER BY
的情况下对结果集进行排序。所以更安全的方法是:
DECLARE
i NUMBER;
BEGIN
FOR rec IN (
SELECT i
FROM (SELECT 1 as i, 1 as ord from dual UNION ALL
SELECT 4 as i, 2 from dual UNION ALL
SELECT 3 as i, 3 from dual UNION ALL
SELECT 2 as i, 4 from dual
) x
ORDER BY ord
) LOOP
DBMS_OUTPUT.PUT_LINE (rec.i);
END LOOP;
end;
答案 1 :(得分:0)
而不是使用 UNION 运算符使用 UNION ALL 运算符,因为 UNION 运算符返回已排序的结果。另一方面, UNION ALL 运算符返回重复未排序结果
尝试以下查询: -
SET SERVEROUTPUT ON;
DECLARE
i NUMBER;
BEGIN
FOR rec IN (
SELECT 1 as i from dual
UNION ALL
SELECT 4 as i from dual
UNION ALL
SELECT 3 as i from dual
UNION ALL
SELECT 2 as i from dual
) LOOP
DBMS_OUTPUT.PUT_LINE (rec.i);
END LOOP;
end;
/
答案 2 :(得分:0)
由于sql语句的一部分,索引的主要起始参考点可能是i-1
。
因此,可能会选择以下光标:
SELECT * FROM
(
SELECT 1 as i from dual
UNION
SELECT 2 as i from dual
UNION
SELECT 3 as i from dual
UNION
SELECT 4 as i from dual
)
ORDER BY sign(i-1), (i-1) desc;