在pl / sql查询块中传递变量值

时间:2016-08-23 09:40:15

标签: sql oracle plsql

我提出了一个问题。请你需要你的专业知识..

PL / SQL块包含变量p_user_id varchar(50)

设置为低于值的值

p_user_id := '101,102,103';

我在PL / SQl块中有如下查询

select Count(*) into v_count
from users
where user_id not in (p_user_id);

每当我调用此PL / SQL块时,v_count值相同,即users表中的记录总数。 Not In子句无法正常工作。请帮忙。

3 个答案:

答案 0 :(得分:1)

users表中没有行user_id的值为'101,102,103'。

如果要将字符串拆分为一组单独的值,则必须做的不仅仅是在not in表达式中使用它。

一些可能的方法:

declare
   p_csvlist varchar2(100) := '2002, 7369, 7499, 7902, 7934';
   v_count integer;
begin
   select count(*) into v_count
   from   emp e
   where  e.empno in
          ( select extractvalue(xt.column_value,'e')
            from   table(xmlsequence
                   ( extract
                     ( xmltype('<coll><e>' || replace(p_csvlist,',','</e><e>') || '</e></coll>')
                     , '/coll/*') )) xt );

   dbms_output.put_line(v_count || ' rows');
end;

或者

declare
   p_csvlist varchar2(100) := '2002, 7369, 7499, 7902, 7934';
   v_count integer;
begin
   select count(*) into v_count
   from   emp e
   where  e.empno in
          ( select regexp_substr(p_csvlist, '[^,]+',1,rownum)
            from   dual
            connect by rownum <= length(p_csvlist) - length(replace(p_csvlist,',')) );

   dbms_output.put_line(v_count || ' rows');
end;

或此(仅适用于数值):

declare
   p_csvlist varchar2(100) := '2002, 7369, 7499, 7902, 7934';
   v_count integer;
begin
   select count(*) into v_count
   from   emp e
   where  e.empno in
          ( select to_number(xt.column_value)
            from   xmltable(p_csvlist) xt );

   dbms_output.put_line(v_count || ' rows');
end;

示例来自我的常见问题解答文章: www.williamrobertson.net/documents/comma-separated.html

答案 1 :(得分:1)

使用LIKE字符串比较:

DECLARE
  p_user_id VARCHAR2(200) := '101,102,103';
  v_count   INT;
BEGIN
  SELECT Count(*)
  INTO   v_count
  FROM   users
  WHERE  ',' || p_user_id || ',' NOT LIKE '%,' || user_id || ',%';
END;
/

使用馆藏:

CREATE OR REPLACE TYPE intlist IS TABLE OF INT;
/

DECLARE
  p_user_id INTLIST := INTLIST( 101, 102, 103 );
  v_count   INT;
BEGIN
  SELECT Count(*)
  INTO   v_count
  FROM   users
  WHERE  user_id NOT MEMBER OF p_user_id;
END;
/

答案 2 :(得分:0)

您可以使用Oracle自身提供的sys.DBMS_DEBUG_VC2COLL --collection数据类型

  DECLARE
      p_user_id sys.DBMS_DEBUG_VC2COLL := sys.DBMS_DEBUG_VC2COLL( 101, 102, 103 );
      v_count   INT;
    BEGIN
      SELECT Count(*)
      INTO   v_count
      FROM   users
      WHERE  user_id not in(select * from table(p_user_id));
    END;
    /