我正在从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"
非常感谢任何帮助。
答案 0 :(得分:2)
我认为您的问题与语句终止符有关(如果您提供实际错误,则更容易看到)。我测试了以下内容并且有效:
[ ... ]$ 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.