在PL / SQL中的With Clause之后使用for循环

时间:2016-05-30 04:47:34

标签: sql oracle plsql with-statement

我正在使用PL / SQL。我正在尝试在with子句中定义临时表之后有一个for循环。但是,我首先得到一个SELECT查询错误。

例如

WITH TMP1 AS (.....), TMP2 AS (......), TMP3 AS (......)

FOR R IN (SELECT DISTINCT ..... FROM TMP1 WHERE .....)
LOOP
SELECT .... FROM TMP2, TMP2 WHERE TMP2.... = R..... ....

我该怎么做?

由于

1 个答案:

答案 0 :(得分:8)

您不能在整个声明之外访问CTE。并且您不能在CTE的最终SELECT之外访问CTE的各个部分。

您需要将整个 CTE(包括最终的SELECT语句)放入游标循环:

FOR R IN (WITH TMP1 AS (.....), 
               TMP2 AS (......), 
               TMP3 AS (......)
          SELECT DISTINCT ..... 
          FROM TMP1 
             JOIN temp2 ON ... 
             JOIN temp3 ON ... 
          WHERE .....)
LOOP
   -- here goes the code that processes each row of the query
END LOOP;