语句未在Oracle中使用“立即执行”执行

时间:2019-11-07 09:50:43

标签: oracle

以下语句在正常执行中执行,但使用EXECUTE IMMEDIATE时不会返回结果。

select distinct 
    FEEDBACKQUESTIONS.FeedbackQuestionId as id,
    FEEDBACKQUESTIONS.FeedbackQuestionId  
from FEEDBACKQUESTIONS 
left join LANGUAGES on FEEDBACKQUESTIONS.LanguageId = LANGUAGES.LanguageId  
where 
    1=1 
    and FEEDBACKQUESTIONS.CrdBy = 1 
order by 
    FEEDBACKQUESTIONS.FeedbackQuestionId desc 
    OFFSET 10 * (1 - 1) ROWS FETCH NEXT 10 ROWS ONLY

1 个答案:

答案 0 :(得分:0)

来自Oracle Docs

  

如果dynamic_sql_statement是SELECT语句,并且您同时省略了in_clause和bulk_collect_into_clause,则execute_immediate_statement将永远不会执行。

如果您想查看SELECT INTO选择值的结果,则可以使用EXECUTE IMMEDIATE子句并将值分配给某个变量。如果您的select语句仅返回一行,则可以使用以下过程。

DECLARE P_CRDBY NUMBER := 1; 
V_ID VARCHAR2(20);
V_QID VARCHAR2(20);
BEGIN 
EXECUTE IMMEDIATE 'SELECT DISTINCT FEEDBACKQUESTIONS.FEEDBACKQUESTIONID AS ID,
                   FEEDBACKQUESTIONS.FEEDBACKQUESTIONID FROM FEEDBACKQUESTIONS 
                   LEFT JOIN LANGUAGES ON FEEDBACKQUESTIONS.LANGUAGEID = LANGUAGES.LANGUAGEID 
                   WHERE 1=1 AND FEEDBACKQUESTIONS.CRDBY = 1 
                   ORDER BY FEEDBACKQUESTIONS.FEEDBACKQUESTIONID DESC 
                   OFFSET 10 * (1 - 1) ROWS FETCH NEXT 10 ROWS ONLY' 
                   INTO V_ID,V_QID ; 
                   --USING P_CRDBY; DBMS_OUTPUT.PUT_LINE(P_CRDBY); 
 DBMS_OUTPUT.PUT_LINE('ID=' || V_ID ||', ID2=' || V_QID);
 END;

对于多行,您可以使用FOR LOOP CURSOR遍历结果集。

DECLARE P_CRDBY NUMBER := 1; 
V_ID VARCHAR2(20);
V_QID VARCHAR2(20);
BEGIN 
FOR MYROW IN (SELECT DISTINCT FEEDBACKQUESTIONS.FEEDBACKQUESTIONID AS ID,
                   FEEDBACKQUESTIONS.FEEDBACKQUESTIONID AS ID2 FROM FEEDBACKQUESTIONS 
                   LEFT JOIN LANGUAGES ON FEEDBACKQUESTIONS.LANGUAGEID = LANGUAGES.LANGUAGEID 
                   WHERE 1=1 AND FEEDBACKQUESTIONS.CRDBY = 1 
                   ORDER BY FEEDBACKQUESTIONS.FEEDBACKQUESTIONID DESC 
                   OFFSET 10 * (1 - 1) ROWS FETCH NEXT 10 ROWS ONLY) 
 --USING P_CRDBY; DBMS_OUTPUT.PUT_LINE(P_CRDBY); 
LOOP                
    DBMS_OUTPUT.PUT_LINE('ID=' || MYROW.ID||', ID2=' || MYROW.ID2);
END LOOP;
END;