使用逻辑运算符作为变量

时间:2017-04-19 07:59:33

标签: sql oracle plsql

我正在尝试在Oracle中执行SQL语句:

FLAG := CASE WHEN @LOOP_COUNT @TARGET_OPERATOR_1 1 THEN 'GREEN'
        ELSE 'RED' 
        END;

这里@Loop_count =一些数字 和@ Target_operator_1是比较运算符'>'或者'<&#;或'> ='

我可以对CASE表达式中的所有组合进行硬编码,但我只想检查它是否可以使用动态SQL。

干杯,

1 个答案:

答案 0 :(得分:2)

如果我理解得很好,您可能需要以下内容:

declare
    /* declare a variable to host a SQL query */
    vSQL    varchar2(1000);
    vResult varchar2(1000);
begin    
    /* build the SQL query as a string and save it into the variable */
    select 'select case ' || chr(13) || chr(10) ||
           listagg ( 'when ' || n1.num || op || n2.num || ' then ''' || n1.num || op || n2.num || '''', chr(13) || chr(10)) 
           within group ( order by 1)
           || ' end' || chr(13) || chr(10) ||
           'from dual'
    into vSQL
    from ( select '<'  as op from dual union all
           select '>'        from dual union all
           select '>='       from dual union all
           select '>='       from dual
         ) operators
    cross join (
                select level as num
                from dual
                connect by level <= 2
               )  n1
    cross join (
                select level -1 as num
                from dual
                connect by level <= 1 
               ) n2;
    --
    /* print the query */
    dbms_output.put_line(vSQL);
    /* run the dynamic query just built and get the result */
    execute immediate vSQL into vResult;
    /* print the result */
    dbms_output.put_line(vResult);
end;    

运行时,这会给出:

select case 
when 1<0 then '1<0'
when 1>0 then '1>0'
when 1>=0 then '1>=0'
when 1>=0 then '1>=0'
when 2<0 then '2<0'
when 2>0 then '2>0'
when 2>=0 then '2>=0'
when 2>=0 then '2>=0' end
from dual
1>0

使用变量,这个:

declare
    vNumVar1    number;
    vNumVar2    number;
    vOpVar      varchar2(2);
    vSQL        varchar2(100);
    vResult     varchar2(100);
begin
    vNumVar1 := 1;
    vNumVar2 := 3;
    vOpVar   := '<='; 
    vSQL := 'select case when ' || vNumVar1 || vOpVar || vNumVar2 || ' then ''something'' end from dual';
    dbms_output.put_line(vSQL);
    execute immediate vSQL
    into vResult;
    dbms_output.put_line(vResult);
end;

给出:

select case when 1<=3 then 'something' end from dual
something