db2 for i : passing a varchar containing comma separated string in an sql procedure in in clause

北城以北 提交于 2021-02-08 10:28:15

问题


i have a string containing comma separated strings in java.. which i m passing to a sql procedure being called in java ... here is example of java string:

    String codeString = "'232/232','34fd/34//'";

code in sql db2 for i:

    create procedure history (in id varchar (3), in code varchar (2000))
   ......
   ......
   begin
   insert into table1
   select date_from, date_to, code
   from table2 
   where table2.serial= id
   and table2.status not in (code); 
   end

this sql procedure is inserting same string in table1.code but it is not excluding table2.status in in clause..

value being inserted in table1.code is '232/232','34fd/34//' (including all single quotes and commas)


回答1:


What you are saying here:

and table2.status not in (code);

is the same as saying:

and table2.status <> code;

You are not saying:

and table2.status not in ('232/232','34fd/34//');

The reason is that it is checking status against the whole of code, not some part of code. The comma separated list in code is not parsed. In fact no variables are parsed. They are taken whole. If you want multiple values in the in predicate, you need either multiple literal values, multiple variables, or some combination of that.

It works for the insert because it is just inserting the whole value of code into the column of table1. No parsing required.

The other option, since you are in a procedure is to parse the comma separated list yourself into an array of strings (not going to show you that here), then use a collection derived table to convert the array to a table that you can use in the in predicate like this:

status not in (select s.string from UNNEST(stringArray) as s(string))



回答2:


try Something like this:

create procedure history (in id varchar (3), in code varchar (2000))

begin
DECLARE stmttxt varchar(2000);
SET stmttxt = 'insert into table1 select date_from, date_to, cast(''' concat replace(code, '''', '''''') concat ''' as varchar(2000)) from table2 where table2.serial= ' concat id concat ' and table2.status not in (' concat code concat ')'; 
EXECUTE IMMEDIATE stmttxt;
end;


来源:https://stackoverflow.com/questions/50310037/db2-for-i-passing-a-varchar-containing-comma-separated-string-in-an-sql-proced

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!