我需要在存储过程中运行递归 CTE,但我无法通过它: SQL0104N 在“SET count=count+1;”之后发现了一个意外的标记“with”。预期的标记可能包括:“”。第 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