在oracle中逗号分隔值为IN函数

时间:2016-06-16 14:15:33

标签: oracle

我正在尝试执行以下查询,但没有得到任何结果。

有人能说出我在做什么错吗?。

DECLARE
  object_types VARCHAR2(200);
  v_object_types VARCHAR2(200);
  l_count number;
BEGIN
  object_types :='TABLE,VIEW';
  select ''''||regexp_replace(object_types, '( )*(,)( )*',''',''')||''''  
         into v_object_types from dual;
  dbms_output.put_line(to_char(v_object_types));
  SELECT count(*) into l_count
    FROM all_objects o where o.object_type IN ('||v_object_types||');
  dbms_output.put_line(l_count);

END;

2 个答案:

答案 0 :(得分:0)

 WHERE variable IN (1,2,3) 

与您现在发送的内容不同

 WHERE variable IN ('1,2,3')  or
 WHERE variable IN ('||v_object_types||')

答案 1 :(得分:0)

您正在尝试动态构建SQL,而是在'||v_object_types||'子句中使用单个字符串文字IN

您可以使用集合来执行此操作:

Oracle安装程序

CREATE TYPE stringlist IS TABLE OF VARCHAR2(200);
/

<强> PL / SQL

DECLARE
  object_types   VARCHAR2(200) := 'TABLE,VIEW';
  v_object_types stringlist;
BEGIN
  SELECT TRIM( BOTH FROM REGEXP_SUBSTR( object_types, '[^,]+', 1, LEVEL ) )
  BULK COLLECT INTO v_object_types
  FROM   DUAL
  CONNECT BY LEVEL <= REGEXP_COUNT( object_types, '[^,]+' );

  FOR i IN 1 .. v_object_types.COUNT LOOP
    dbms_output.put_line( v_object_types(i) );
  END LOOP;

  SELECT count(*)
  INTO   l_count
  FROM   all_objects
  WHERE  object_type MEMBER OF v_object_types;

  dbms_output.put_line(l_count);
END;
/

或使用动态sql:

DECLARE
  object_types   VARCHAR2(200) := 'TABLE,VIEW';
  v_sql          VARCHAR2(200);
  l_count        INTEGER;
BEGIN
  v_sql := 'SELECT count(*) FROM all_objects WHERE  object_type IN ('
             || REGEXP_REPLACE( object_types, ' *(.+?) *(,|$)', '''\1''\2' )
             || ')';

  EXECUTE IMMEDIATE v_sql INTO l_count;

  dbms_output.put_line(l_count);
END;
/