【问题标题】:Use Recursive CTE in DB2 stored proc在 DB2 存储过程中使用递归 CTE
【发布时间】:2011-03-18 04:57:53
【问题描述】:

我需要在存储过程中运行递归 CTE,但我无法通过它: SQL0104N 在“SET count=count+1;”之后发现了意外的标记“with” "。预期的标记可能包括:""。LINE NUMBER=26。

我的 google-fu 显示了几个类似的主题,但没有一个具有分辨率。

查询功能在存储过程之外按预期运行,所以我希望我缺少一些语法糖可以让它工作。同样,proc 在没有查询的情况下编译和工作。

这是一个人为的例子:

--setup
create table tree (id integer, name varchar(50), parent_id integer);
insert into tree values (1, 'Alice', null);
insert into tree values (2, 'Bob', 1);
insert into tree values (3, 'Charlie', 2);

-

- the proc
create or replace procedure testme() RESULT SETS 1 LANGUAGE SQL
BEGIN
DECLARE SQLSTATE CHAR(5);
DECLARE SQLCODE integer default 0;
DECLARE count INTEGER;
DECLARE sum INTEGER;
DECLARE total INTEGER;
DECLARE id INTEGER;
DECLARE curs CURSOR WITH RETURN FOR 
select count,sum from sysibm.sysdummy1;

DECLARE hiercurs CURSOR FOR 
select id from tree order by id;
SET bomQuery='';
PREPARE stmt FROM bomQuery;
SET count = 0;
SET sum = 0;
set total = 0;
OPEN hiercurs;
FETCH hiercurs INTO id;
WHILE (SQLCODE <> 100) DO
SET count=count+1;

with org (level,id,name,parent_id) as
(select 1 as level,root.id,root.name,root.parent_id from tree root where root.id=id
union all
select level+1,employee.id,employee.name,employee.parent_ id from org boss, tree employee 
where level < 5 and employee.parent_id=boss.id)
select count(1) into sum from org;

SET total=total+sum;
FETCH hiercurs INTO id;
END WHILE;
CLOSE hiercurs;
OPEN curs;
END

【问题讨论】:

    标签: stored-procedures db2 recursion common-table-expression


    【解决方案1】:

    db2 中的 cte 似乎无法识别查询的标量结果,因此它不会让 select 起作用(在 Oracle 或 SQLServer 上不是问题)...解决方案是打开一个游标并取而代之的是 FETCH INTO(而不是 SELECT INTO)。

    【讨论】:

      【解决方案2】:

      除了 rjb 建议将 CTE 查询包含在游标中之外,您还可以将 CTE 填充到用户定义的函数或视图中,然后将针对该对象的直接选择编码到您的存储过程中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-25
        • 2015-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-14
        • 2013-11-13
        相关资源
        最近更新 更多