我在oracle中有一存储过程中有:
insert into tbb1(a,b)
select a ,sum(b) from table
where a in (sMC)
group by a
语句;
其中sMc为参数;
我在delphi 中
调用
sp_sp1,params[0].asstring:='''北京'',''四川''';
sp_sp1.execsql;
可是为空!
...全文
1583打赏收藏
in 的 问题
我在oracle中有一存储过程中有: insert into tbb1(a,b) select a ,sum(b) from table where a in (sMC) group by a 语句; 其中sMc为参数; 我在delphi 中 调用 sp_sp1,params[0].asstring:='''北京'',''四川'''; sp_sp1.execsql; 可是为空!
in 是不能这么用的,oracle会把整个变量作为一个字符串然后判断纪录中值是否和这整个字符串相等,你的语句执行的效果等同于:
insert into tbb1(a,b)
select a ,sum(b) from table
where a = '''北京'',''四川'''
group by a;
这样返回0个纪录当然是正常的。
我做了一下试验,可以验证这一点:
SQL> select * from test_1201
2 where id in ('1','2')
3 /
ID
----------
1
2
SQL> declare
2 w_tmp varchar2(100);
3 w_count number(10);
4 begin
5 w_tmp := '''1'',''2''';
6 select count(*) into w_count
7 from test_1201
8 where id in (w_tmp);
9 dbms_output.put_line('Count selected: '||w_count);
10 end;
11 /
Count selected: 0
PL/SQL procedure successfully completed.
你的问题恐怕最方便的解决办法是用动态sql(你用的oracle版本必须在815以上),把插入新纪录的语句用字符串表达,然后execute immediate;但这样就没起到存储过程预编译的效果。
declare
w_str varchar2(255);
...
begin
...
w_str := 'insert into tbb1(a,b) select a ,sum(b) from table '
|| 'where a in (' || sMC || ') '
|| 'group by a';
execute immediate w_str;
...
end;