Oracle PL/SQL 在原始和分层之间切换 select
Oracle PL/SQL switch between raw and hierarchical select
我需要在一个 Oracle PL/SQL select 中根据某些变量在原始 select 和分层 select 语句之间切换。但是,不能在 select 中使用 If 语句。
例如,我有分层语句
select a.*
from myTable a
start with a.id = varValue
connect by prior a.id = a.parentId
如果某些 varCondition 为 0。
如果 varCondition = 1 那么 select 应该给出与语句结果相同的结果
select a.* from myTable a where a.id = varValue
类似于 select a.* from myTable a start with a.id = varValue connect by prior a.id = decode(varCondition, ...)
可能吗?
你可以这样做:
PROCEDURE GET_RECORDS(v_action IN VARCHAR2)
IS
CURSOR get_records
IS
IF(v_action = 'DO THIS') THEN
SELECT * from <THIS>;
ELSE
SELECT * from <THAT>;
END IF;
BEGIN
OPEN get_records;
FETCH get_records
INTO v_thing;
v_loop := 0;
WHILE get_records%FOUND
LOOP
FETCH get_records
INTO v_thing;
END LOOP;
CLOSE get_records;
END;
(来源:[Conditionally define a Cursor in Oracle)
或者你可以使用这个:
declare
SQL_Text varchar2(32760) := 'select * from dual'; --your query goes here
SQL_Text2 varchar2(32760) := 'select * from dual'; --your query goes here
cur sys_refcursor;
begin
IF some_condition THEN
open cur for SQL_Text;
ELSE
open cur for SQL_Text2;
END IF;
-- ...
end;
您可以在 CONNECT BY
子句中使用 NULL
以确保当您的 varCondition
变量为 1
时它始终为假,并在其他情况下使用层次结构:
SELECT *
FROM myTable
START WITH id = varValue
CONNECT BY PRIOR id = DECODE( varCondition, 1, NULL, parentId )
我需要在一个 Oracle PL/SQL select 中根据某些变量在原始 select 和分层 select 语句之间切换。但是,不能在 select 中使用 If 语句。 例如,我有分层语句
select a.*
from myTable a
start with a.id = varValue
connect by prior a.id = a.parentId
如果某些 varCondition 为 0。
如果 varCondition = 1 那么 select 应该给出与语句结果相同的结果
select a.* from myTable a where a.id = varValue
类似于 select a.* from myTable a start with a.id = varValue connect by prior a.id = decode(varCondition, ...)
可能吗?
你可以这样做:
PROCEDURE GET_RECORDS(v_action IN VARCHAR2)
IS
CURSOR get_records
IS
IF(v_action = 'DO THIS') THEN
SELECT * from <THIS>;
ELSE
SELECT * from <THAT>;
END IF;
BEGIN
OPEN get_records;
FETCH get_records
INTO v_thing;
v_loop := 0;
WHILE get_records%FOUND
LOOP
FETCH get_records
INTO v_thing;
END LOOP;
CLOSE get_records;
END;
(来源:[Conditionally define a Cursor in Oracle)
或者你可以使用这个:
declare
SQL_Text varchar2(32760) := 'select * from dual'; --your query goes here
SQL_Text2 varchar2(32760) := 'select * from dual'; --your query goes here
cur sys_refcursor;
begin
IF some_condition THEN
open cur for SQL_Text;
ELSE
open cur for SQL_Text2;
END IF;
-- ...
end;
您可以在 CONNECT BY
子句中使用 NULL
以确保当您的 varCondition
变量为 1
时它始终为假,并在其他情况下使用层次结构:
SELECT *
FROM myTable
START WITH id = varValue
CONNECT BY PRIOR id = DECODE( varCondition, 1, NULL, parentId )