无法在DB2中通过游标打印数据

au9on6nz  于 2022-11-07  发布在  DB2
关注(0)|答案(1)|浏览(189)

编码:

BEGIN   
  DECLARE EMPID INT DEFAULT 0;
  CALL dbms_output.put_line ('EMPID-' || EMPID);
  DECLARE c1 CURSOR FOR  select EMPLOYEE_ID from EMP.EMPLOYEESDET;
  OPEN c1;
  LOOP
  FETCH c1  INTO EMPID;
  CALL dbms_output.put_line ('Display EMPID-' || EMPID);
  end loop;
  close c1;
END
@

错误:

[Code: -104, SQL State: 42601]  An unexpected token <cursor declaration> was found following.  

Expected tokens may include:  <SQL statement>.. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.28.11
new9mtju

new9mtju1#

在使用匿名块和复合SQL(内联)时,有效的语句是SQL语句的子集。documentation声明哪些语句是有效的。
具体来说,您只能在复合SQL(编译)块中(即在例程/存储过程中)使用DECLARE CURSOR。
相反,您应该在匿名区块中使用FOR陈述式,如下所示:

BEGIN   
  DECLARE EMPID INT DEFAULT 0;
  CALL dbms_output.put_line ('EMPID-' || EMPID );
  FOR ROW AS select EMPLOYEE_ID from EMP.EMPLOYEESDET
  DO
      CALL dbms_output.put_line ('Display EMPID- ' || EMPID);
  end FOR;
END
@

如果可能,您的代码应该单独处理EMPID为NULL的情况(例如,使用coalesce(empid,...))。

相关问题