代码之家  ›  专栏  ›  技术社区  ›  Coding Duchess

动态SQL中空参数的PL/SQL处理

  •  1
  • Coding Duchess  · 技术社区  · 7 年前

    procedure my_proc(p_first VARCHAR2, p_second NUMBER, p_third NUMBER DEFAULT NULL, p_fouth NUMBER DEFAULT NULL)
    IS
    str varchar2(3200);
    v1 VARCHAR2(20);
    v2 VARCHAR2(20);
    v3 VARCHAR2(20);
    str2 varchar2(1000);
    
    begin
    
    str2:='SELECT t2.c1,t2.c2, my_func1(t2.c3, '||p_third||') FROM ';
    
    if p_third=3 then
            str:= 't1,t2,t3 where t1.c1=t2.c1 and t2.c1=t3.c1 and t1.c1=p_first ;' ;
    elsif p_third=2 then
            str:=' t1,t2,t4 where t1.c1=t2.c1 and t2.c1=t4.c1 and t2.c1=p_second ;' ;
    else
            str:='t2 where t2.c1=p_second ;';
    end if;
    
    str2:=str2 || str;
    
    dbms_output.put_line(str2);
    EXECUTE IMMEDIATE  str2 into v1,v2,v3;
    
    --dbms_output.put_line(v1||','||v2||','||v3);
    
    end;
    

    其中pçthird为空,因此sql结果为:

    SELECT t2.c1,t2.c2, my_func1(t2.c3, ) FROM t1,t2,t4 where t1.c1=t2.c1 and t2.c1=t4.c1 and t2.c1=p_second;
    

    我需要的是:

    SELECT t2.c1,t2.c2, my_func1(t2.c3) FROM t1,t2,t4 where t1.c1=t2.c1 and t2.c1=t4.c1 and t2.c1=p_second;
    

    每当第三个是 NULL

    2 回复  |  直到 7 年前
        1
  •  1
  •   Littlefoot    7 年前

    用例:

    str2:='SELECT t2.c1,t2.c2, my_func1(t2.c3' ||
      case when p_third is null then null
           else ', ' || p_third
      end || ') FROM ';
    
        2
  •  1
  •   Littlefoot    7 年前

    在上面再加一张支票怎么样

    IF p_third IS NOT NULL THEN
       str2:='SELECT t2.c1,t2.c2, my_func1(t2.c3, '||p_third||') FROM ';
    ELSE
       str2:='SELECT t2.c1,t2.c2, my_func1(t2.c3) FROM ';
    END IF: