DB2使用存储过程运行SQL语句时务必要escape

Categories: Database; Tagged with: ; @ October 5th, 2010 16:12

譬如: 我Alert一个Column的Nullable后, 需要运行如下语句:

CALL SYSPROC.ALTOBJ ( ‘APPLY_CONTINUE_ON_ERROR’, ‘CREATE TABLE ADMINISTRATOR.TB6 (
ID BIGINT  NOT NULL  WITH DEFAULT 26 ,
NAME VARCHAR (128)  NOT NULL WITH DEFAULT ‘TOM’) IN USERSPACE1 COMPRESS YES ‘, -1, ? );

注意看, NAME中名字都将默认叫做TOM, 但不论通过JDBC还是DB2Control Center运行, 都会出现错误:

SQL0104N  An unexpected token "TOM" was found following "NULL WITH DEFAULT ‘"….

User response:
Examine and correct the statement in the area of the specified token.

sqlcode: –104 
sqlstate: 42601

这不是让我费解的问题, 平日里咱最擅长的就是制造一大堆问题. 但DB2CC很贱, 生成出来的SQL语句就是这样, 但它死活就是有错误.

解决方法:

对普通的SQL来说, 无需转义, 可直接运行; 但作为存储过程的参数, 所以必须先转义(不论运行在DB2CC还是通过JDBC)

否则这句代码就紊乱了, 引号之间就被TOM搞乱套了.

正解:(注意看引号 ‘TOM’ => ”TOM”)

CALL SYSPROC.ALTOBJ ( ‘APPLY_CONTINUE_ON_ERROR’, ‘CREATE TABLE ADMINISTRATOR.TB6 (
ID BIGINT  NOT NULL  WITH DEFAULT 26 ,
NAME VARCHAR (128)  NOT NULL WITH DEFAULT ”TOM”) IN USERSPACE1 COMPRESS YES ‘, -1, ? );



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.