IBM DB2 控制循环
IBM DB2 Control Loop
我正在从 MS SQL 服务器迁移到 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"
非常感谢任何帮助。
我假设您的问题与语句终止符有关(如果您提供了您遇到的实际错误,则更容易查看)。我测试了以下内容并且有效:
[ ... ]$ 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.
这里我使用@作为语句终止符,因为 ;有特殊的意义。如果您不想更改语句终止符,一个技巧是 "hide" the ;通过在行尾添加注释在复合语句中:
[ ... ]$ 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.
我正在从 MS SQL 服务器迁移到 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"
非常感谢任何帮助。
我假设您的问题与语句终止符有关(如果您提供了您遇到的实际错误,则更容易查看)。我测试了以下内容并且有效:
[ ... ]$ 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.
这里我使用@作为语句终止符,因为 ;有特殊的意义。如果您不想更改语句终止符,一个技巧是 "hide" the ;通过在行尾添加注释在复合语句中:
[ ... ]$ 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.