oracle pl / sql ora-01722错误

时间:2009-06-09 05:06:39

标签: sql oracle ora-01722

我的程序中有一个简单的oracle语句:

update org.security_training_question a 
set a.actv_indr = 'N' where a.qstn_id in (v_qstns_to_delete);

v_qstns_to_delete是传递的参数。它是一个varchar2字段,a.qstn_id是一个数字字段。

调用存储过程时,对于v_qstns_to_delete,我传递以下字符串:“24,43,23,42,21”。

当我运行语句输出存储过程然后它运行正常,但当我作为存储过程运行时,我在上面的行上收到错误,说错误号码。

有任何线索吗?

2 个答案:

答案 0 :(得分:2)

您不能将“in”子句与此类变量一起使用。其中一个方法是

declare stmt varchar2(4000);
begin
  stmt := 'update org.security_training_question a set a.actv_indr = ''N'' where a.qstn_id in ('||v_qstns_to_delete||')';
  execute immediate stmt;
end;

答案 1 :(得分:1)

如果v_qstns_to_delete是varchar,您需要稍微转换一下,让Oracle了解其中可能有多个项目。一种方法是将字符串转换为项目表。

假设qstn_id是NUMBER列,您可以:

SQL> CREATE TYPE tab_number AS TABLE OF NUMBER;
  2  /

Type created

SQL> CREATE OR REPLACE FUNCTION to_tab_number(p_in VARCHAR2,
  2                                           p_separator VARCHAR2 DEFAULT ',')
  3        RETURN tab_number AS
  4     l_result tab_number := tab_number();
  5     l_tail   LONG := p_in;
  6  BEGIN
  7     WHILE l_tail IS NOT NULL LOOP
  8        l_result.EXTEND;
  9        IF instr(l_tail, p_separator) != 0 THEN
 10           l_result(l_result.COUNT) := to_number(substr(l_tail,
 11                                                 1,
 12                                                 instr(l_tail, p_separator) - 1));
 13           l_tail := substr(l_tail, instr(l_tail, p_separator) + 1);
 14        ELSE
 15           l_result(l_result.COUNT) := to_number(l_tail);
 16           l_tail := NULL;
 17        END IF;
 18     END LOOP;
 19     RETURN l_result;
 20  END;
 21  /

Function created

然后,您可以将字符串转换为SQL中的数字表:

SQL> SELECT * FROM TABLE(to_tab_number('24, 43, 23, 44, 21'));

COLUMN_VALUE
------------
          24
          43
          23
          44
          21

要在列表中执行变量:

SQL> SELECT object_id, owner
  2    FROM all_objects
  3   WHERE object_id IN (SELECT column_value FROM TABLE(to_tab_number('18,19,20')));

 OBJECT_ID OWNER
---------- ------------------------------
        18 SYS
        19 SYS
        20 SYS

askTom上有关同一主题的更多内容。