1

我正在从 MS SQL Server 迁移到 IBM DB2(9.7 版)。尝试使用局部变量(不是存储过程的一部分)编写复合 SQL While 循环,例如 -

BEGIN ATOMIC
   DECLARE i INT DEFAULT 12;
     WHILE i > 0 
     "DO ....";
     SET COUNT = COUNT - 1;
     END WHILE;
 END

但是我在第一行声明变量时遇到错误-

SQL0104N  An unexpected token "12" was found following "ECLARE I INT DEFAULT". Expected tokens may include:  "END-OF-STATEMENT"

任何帮助是极大的赞赏。

4

1 回答 1

3

我认为您的问题与语句终止符有关(更容易查看您是否提供了您得到的实际错误)。我测试了以下内容并且它有效:

[ ... ]$ cat aa.sql 

CREATE TABLE TEMP_ITERATIONS ( X VARCHAR(50) ) @

BEGIN ATOMIC 
    DECLARE i INT DEFAULT 12; 
    WHILE i > 0 DO 
        INSERT INTO TEMP_ITERATIONS VALUES ('IT'|| RTRIM(CHAR(i))); 
        SET i = i - 1; 
    END WHILE; 
END @

[ ... ]$ db2 -td@ -f aa.sql

DB20000I  The SQL command completed successfully.
DB20000I  The SQL command completed successfully.

[ ... ]$ db2 "select * from TEMP_ITERATIONS"

X                                                 
--------------------------------------------------
IT12                                              
IT11                                              
IT10
[...]
12 record(s) selected.

在这里,我使用 @ 作为语句终止符,因为 ; 有特殊的意义。如果您不想更改语句终止符,一个技巧是“隐藏” ; 通过在行尾添加注释在复合语句中:

[ ... ]$ cat aa.sql 

CREATE TABLE TEMP_ITERATIONS ( X VARCHAR(50) ) ;

BEGIN ATOMIC 
    DECLARE i INT DEFAULT 12; --
    WHILE i > 0 DO 
        INSERT INTO TEMP_ITERATIONS VALUES ('IT'|| RTRIM(CHAR(i))); --
        SET i = i - 1; --
    END WHILE; --
END ;

[ ... ] db2 -tf aa.sql
DB20000I  The SQL command completed successfully.
DB20000I  The SQL command completed successfully.

[ ... ]$ db2 "select * from TEMP_ITERATIONS"

X                                                 
--------------------------------------------------
IT12                                              
IT11                                              
IT10
[...]
12 record(s) selected.
于 2015-08-25T20:16:55.367 回答