在DB2 PL SQL的For循环游标内查询“With”子句

时间:2013-12-09 17:31:46

标签: for-loop cursor db2 with-clause sql-pl

我有一个非常复杂的查询,其中包含一个“With”子句。在DB2 Client上执行时,此查询可以正常工作。但是,如果在PL SQL存储过程的For循环游标内使用相同的查询,则它不起作用。在尝试将存储过程应用于数据库时,它会产生语法错误,如下所示。

SQL0104N  An unexpected token "AS" was found following "col5 )

for循环如下所示。

FOR records AS cursors CURSOR FOR
  (
    WITH
    temp1
    (
        col1, col2, col3, col4, col5
    )
    AS 
    (
        SELECT
        col1, col2, col3, col4, col5
    FROM
        table1
    )
    WITH
    temp2
    (
        col6, col7, col8, col9, col10
    )
    AS
    (
        SELECT
        col6, col7, col8, col9, col10
    FROM
        table2
    )
    SELECT col1, col2, col3, col4, col5, col6, co7, col8, col9, col10
    FROM temp1, temp2
)
DO
    -- Do Something here.
END FOR;

请帮助解决这个问题。提前谢谢。

2 个答案:

答案 0 :(得分:0)

你有两个问题。首先,FOR语句不正确;它应该引用先前声明的游标:

...
CURSOR mycur IS WITH ... SELECT ...;
...
FOR rec IN mycur LOOP ...

其次,查询

WITH temp1 ( col1, col2, col3, col4, col5 ) AS ( 
  SELECT col1, col2, col3, col4, col5 FROM table1 
) 
WITH temp2 ( col6, col7, col8, col9, col10 ) AS ( 
  SELECT col6, col7, col8, col9, col10 FROM table2

无效,永远不会自行运行,所以你声称它在CLP中执行是不真实的。

答案 1 :(得分:0)

最后我把这件事搞定了。解决方案非常简单。它是删除括起查询的大括号,如下所示。

 FOR records AS cursors CURSOR FOR 

    WITH
    temp1
    (
        col1, col2, col3, col4, col5
    )
    AS 
    (
        SELECT
        col1, col2, col3, col4, col5
    FROM
        table1
    )

    WITH
    temp2
    (
      col6, col7, col8, col9, col10
    )
    AS
    (
        SELECT
        col6, col7, col8, col9, col10
    FROM
        table2 
    )
    SELECT col1, col2, col3, col4, col5, col6, co7, col8, col9, col10
    FROM   temp1, temp2
DO
    --  Do Something here.

END  FOR  ;

我不确定为什么会这样。它适用于任何其他没有WITH子句的普通查询。