在for循环中选择带case语句的变量

时间:2017-11-09 08:16:45

标签: sql oracle plsql

foo 变量应在 for 循环中填充 select case ,然后输出。我在异常中使用了 goto end_loop 引用,因此循环可以继续。 在我提出异常之前,我有一个ORA-01403错误。现在我有一个ORA-01422错误。没有case语句的其他选择工作正常。

declare
foo varchar2(2000); 
BEGIN   
   FOR rec IN (SELECT something FROM somewhere)  
    LOOP
        BEGIN
          Select case when attribute = 'something' then '1' end into foo from somewhere where some_condition;   
          DBMS_OUTPUT.put_line( 'Something' || foo);     
          EXCEPTION
           WHEN NO_DATA_FOUND THEN
               foo := NULL;
               goto end_loop;     
        END;
        <<end_loop>>
        null;
    END LOOP; 
END;

修改

更详细

declare
opdatum varchar2(2000);  
opdiagnose varchar2(2000);  
d_op varchar2(2000); 
some_variable varchar2(2000); 
BEGIN   
   FOR rec IN (SELECT p.name, p.vorname, p.geburtsdatum, a.kis_id, kg.kg_id FROM kg_eintraege kg
   INNER JOIN aufenthalte a
   ON kg.patient_nr = a.patient_nr
   and kg.fall_nr = a.fall_nr
   INNER JOIN personen p
   ON a.patient_nr = p.pat_nr
   WHERE kg.kgtitel_nr = xxxxxxa
   and a.kis_id = xxxxxxb)  
    LOOP
        BEGIN
          Select kurztext into opdatum from kg_eintraege where kontext = rec.kg_id and kgtitel_nr = xxxxxxc;  
          Select text into opdiagnose from kg_eintraege where kontext = rec.kg_id and kgtitel_nr = xxxxxxd;  
          Select text into d_op from kg_eintraege where kontext = rec.kg_id and kgtitel_nr = xxxxxxe; 
          Select case when kurztext = 'Something' then '1' end into some_variable  from kg_eintraege where kontext = rec.kg_id and kgtitel_nr = xxxxxxf;   
          DBMS_OUTPUT.put_line(rec.name || '    ' || rec.vorname || '    ' || TO_CHAR(rec.geburtsdatum, 'DD.MM.YYYY')
          || '    ' || rec.kis_id || '    ' ||  opdatum|| '    ' || opdiagnose || 
           '    ' || d_op || '    ' || some_variable 
          );     
          EXCEPTION
           WHEN NO_DATA_FOUND THEN
               some_variable := NULL;
               goto end_loop;     
        END;
        <<end_loop>>
        null;
    END LOOP; 
END;

更新

案件陈述似乎没问题。问题是select中的某些行为null。

UPDATE2

不需要例外。

解决方案:

 select nvl((select case when kurztext = 'Something' then '1' end from kg_eintraege where kontext = rec.kg_id and kgtitel_nr = xxxxxxf and kurztext = 'Something'), 'NOT_FOUND') into some_variable from dual 

感谢NikNik的帮助。

1 个答案:

答案 0 :(得分:0)

你的问题不在于CASE,而是你的WHERE条件正在回溯超过1条记录或0条记录。

有关详细信息,请查看here

在第二种情况下,您可以执行this

select  nvl(  (your_case),  'NOT_FOUND'  )  into  foo  from dual;