iSeries IDB2 - 在存储过程中声明返回结果集

时间:2016-08-11 21:50:42

标签: sql db2 ibm-midrange db2-400

我试图在存储过程中声明并设置变量的值,该变量通过游标返回结果集。我这样做是因为我计划变量来帮助过滤结果。

当我只用光标发表声明时,一切正常。这是代码:

CREATE OR REPLACE PROCEDURE MYLIB.MYTEST()
DYNAMIC RESULT SETS 1
LANGUAGE SQL 
SPECIFIC MYTEST 
NOT DETERMINISTIC 
READS SQL DATA 
CALLED ON NULL INPUT 

BEGIN

DECLARE C1 CURSOR WITH RETURN FOR 
SELECT * FROM SOMELIB.SOMEFILE 
FETCH FIRST 100 ROWS ONLY;
OPEN C1; 
END; 

当我尝试声明并设置变量时,我得到一个错误。这是代码:

CREATE OR REPLACE PROCEDURE MYLIB.MYTEST()
DYNAMIC RESULT SETS 1
LANGUAGE SQL 
SPECIFIC MYTEST 
NOT DETERMINISTIC 
READS SQL DATA 
CALLED ON NULL INPUT 

BEGIN

DECLARE SOMENAME VARCHAR(10);
SET SOMENAME = 'JOHN';

DECLARE C1 CURSOR WITH RETURN FOR 
SELECT * FROM SOMELIB.SOMEFILE WHERE LASTNAME = SOMENAME
FETCH FIRST 100 ROWS ONLY;
OPEN C1; 
END; 

我收到的错误如下:

SQL State: 42601
Vendor Code: -104
Message: [SQL0104] Token C1 was not valid. Valid tokens: GLOBAL. 
Cause . . . . . :   A syntax error was detected at token C1.  
Token C1 is not a valid token.  A partial list of valid tokens is GLOBAL.    
This list assumes that the statement is correct up to the token.  
The error may be earlier in the statement, but the syntax of the statement 
appears to be valid up to this point. Recovery  . . . :   
Do one or more of the following and try the request again: -- 
Verify the SQL statement in the area of the token C1. Correct the statement.
The error could be a missing comma or quotation mark, it could be a
misspelled word, or it could be related to the order of clauses. -- 
If the error token is <END-OF-STATEMENT>, correct the SQL statement 
because it does not end with a valid clause.

有人能告诉我在返回结果集的存储过程中声明和设置变量的正确语法吗?它甚至可能吗?

1 个答案:

答案 0 :(得分:5)

您需要在可执行代码之前完成所有DECLARE。移动SET

CREATE OR REPLACE PROCEDURE MYLIB.MYTEST()
DYNAMIC RESULT SETS 1
LANGUAGE SQL 
SPECIFIC MYTEST 
NOT DETERMINISTIC 
READS SQL DATA 
CALLED ON NULL INPUT 

BEGIN

-- Declaration statements
DECLARE SOMENAME VARCHAR(10);
DECLARE C1 CURSOR WITH RETURN FOR 
SELECT * FROM SOMELIB.SOMEFILE WHERE LASTNAME = SOMENAME
FETCH FIRST 100 ROWS ONLY;

-- Executable statements 
SET SOMENAME = 'JOHN';
OPEN C1; 
END;