Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql oracle光标值因条件而异_Sql_Oracle_Stored Procedures_Cursor_Conditional - Fatal编程技术网

Sql oracle光标值因条件而异

Sql oracle光标值因条件而异,sql,oracle,stored-procedures,cursor,conditional,Sql,Oracle,Stored Procedures,Cursor,Conditional,我想问一下,是否可以在游标声明上分配一个变量 CURSOR cur_name IS <variable_name> 如果v_cnt为0,则光标将为: cursor cur_name IS select * from tab_name1 where cond1; cursor cur_name IS select * from tab_name2 where cond1 and cond2; 如果v_cnt>0,光标将为:

我想问一下,是否可以在游标声明上分配一个变量

CURSOR cur_name IS <variable_name>
如果v_cnt为0,则光标将为:

 cursor cur_name IS 
    select * from tab_name1
    where cond1;
    cursor cur_name IS 
    select * from tab_name2
    where cond1
    and cond2;
如果v_cnt>0,光标将为:

 cursor cur_name IS 
    select * from tab_name1
    where cond1;
    cursor cur_name IS 
    select * from tab_name2
    where cond1
    and cond2;
我想知道我是否可以在光标上指定的select上执行if-else和then-concat

    cursor cur_name IS 
    select * from tab_name
    if v_cnt > 0
    where cond2;
    else 
    where cond1;
如果你需要更多的细节,请告诉我。
感谢您的反馈。

为什么不使用类似

select  * 
from    tab_name 
WHERE   (v_cnt = 0  AND cond1)
OR      (v_cnt > 0  AND cond2)

你在找这样的东西吗

DECLARE
  V_CNT VARCHAR2(20);

  CURSOR C1
  IS
  SELECT * from Tab1;

  CURSOR C2
  IS
  SELECT * from Tab2;   

BEGIN
  SELECT COUNT(*) INTO V_CNT FROM Table_Name;
    IF V_CNT > 0 THEN
       OPEN C1;
         --code
        Close C1;
    ELSE
       OPEN C2;
          --code
       CLOSE C2;
    END IF;
 END;

如果光标非常动态,请使用以下内容:

 declare
  c sys_refcursor;
  <here declare the record you would like fetch results to> 
 begin
  open c for 'you query in quotes as the string that you created before regarding your     conditions';
  loop
   FETCH c INTO your record;
   EXIT WHEN c%NOTFOUND;
  end loop;
 end;

无论如何,我们都要调查一下。根据我的观点,它描述了你的情况。

有很多方法可以做到这一点,其中涉及到很多权衡

亚历山大·托卡列夫的答案是最灵活的。但动态SQL可能很棘手,依赖性问题不会在编译时出现,等等。Balaji Sukumaran的答案不太灵活,但更简单,并将代码分成更小的块

如果选定的列始终相同,则可以使用如下方法:

cursor cur_name(v_cnt number) is
select *
from tab_name1
where 1=1 /*condition 1*/
    and v_cnt > 0
---------
union all
---------
select *
from tab_name2
where 2=2 /*condition 2*/
    and (v_cnt is null or v_cnt <= 0);
它把所有的东西放在一起,这比巴拉吉的回答更令人困惑。但有时最好将所有逻辑放在一个SQL中。它可能有助于减少重复逻辑


另外,您不必担心Oracle实际上同时使用这两个查询,而且运行速度很慢。知道有一个bind变量控制使用哪个查询就足够聪明了。这就是解释计划中的筛选步骤所做的。

抱歉,我认为我的示例过于简化了。。。根据v_cnt值,某些条件和表格也会有所不同。所以我希望我可以将select分配给一个变量,并向其附加任何代码行。您好,谢谢您的回答,但我认为如果我更改列,将不会有效率,我必须将其更改为两个游标..: