2017-04-19 21 views
1

我試圖執行Oracle中的SQL語句:執行與邏輯運算符聲明的變量

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

這裏@Loop_count =一定數量 和@ Target_operator_1是操作比較「>」或'< '或‘> =’

我可以硬編碼CASE表達式內的所有組合,但我只是想檢查,如果可能與動態SQL。

乾杯,

+0

在你的問題中沒有SQL語句。這可能是PL/SQL代碼,但不是SQL語句。 – Seyran

+2

這不是有效的Oracle SQL或PL/SQL;在PL/SQL你的錯誤'PLS-00103:出現符號「@」在需要下列之一時:。...符號「@」被忽略「' - 你確定它不是來自SQL Server或一些其他的RDBMS? – MT0

+0

我寫@區分變量名..和是的,它是一個PLSQL腳本的一部分.. :) – thealchemist

回答

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; 

GI ves:

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

我想你是誤會我的問題。我所擁有的一切變量..喜歡NUM1,邏輯運算符和NUM2 ..我想執行這樣的SQL語句。與一個CASE功能..所以這將是情況NUM1 logical_operator NUM2那麼「綠色」(它讀成2> 1,則「綠色」) – thealchemist

+0

這是沒有什麼不同,只是編輯向你展示 – Aleksej

+0

你是不可思議的:)我真誠的感謝你的伴侶.. – thealchemist