如何在varchar列中搜索varchar变量? PL SQL

时间:2015-01-07 15:05:43

标签: oracle plsql

我想知道Oracle 11g中的某些特定职责是否存在于数据库中。

假设我们有10个职责,我想搜索它们是否存在于包含60的数据库中。

如何在varchar列中搜索varchar变量?

对于单变量,它应该很容易..

declare
var varchar(100);
begin
var:='&var';
if var is not null 
then
select responsibility_name  FROM  apps.fnd_responsibility_tl where responsibility_name  _ ?
dbms_output.put_line(var||' EXISTS'); 
else
dbms_output.put_line(var||' ERROR'); 
end if;
end;
/

1 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点,简单的方法,以及您使用PL / SQL在问题中请求的方式。

首先,使用SQL的简单方法。这使用从a blog post by Arunkumar Ramamoorthy获取的技巧,使用REGEXP_SUBSTR和CONNECT BY将逗号分隔列表转换为行。

WITH  search_criteria AS (
   SELECT   TRIM(REGEXP_SUBSTR('&search_criteria','[^,]+', 1, LEVEL)) AS search_responsibility
   FROM     dual
   CONNECT BY
            TRIM(REGEXP_SUBSTR('&search_criteria', '[^,]+', 1, LEVEL)) IS NOT NULL
)

SELECT   s.search_responsibility,  
         CASE WHEN r.responsibility_name IS NULL THEN 'ERROR' ELSE 'EXISTS' END AS status
FROM     search_criteria s
LEFT OUTER JOIN
         apps.fnd_responsibility_tl r ON (r.responsibility_name = s.search_responsibility);

其次,使用PL / SQL和DBMS_OUTPUT的方式更为复杂。它使用与SQL版本相同的原则,但使用游标检查每个职责是否存在,输出EXISTS或ERROR消息。

CREATE OR REPLACE PROCEDURE check_responsibilities (p_search_criteria IN VARCHAR2)
IS
  CURSOR c_responsibilities (p_responsibilities IN VARCHAR2)
  IS
   SELECT   TRIM(REGEXP_SUBSTR(p_responsibilities,'[^,]+', 1, LEVEL)) AS search_responsibility
   FROM     dual
   CONNECT BY
            REGEXP_SUBSTR(p_responsibilities, '[^,]+', 1, LEVEL) IS NOT NULL;

   lv_temp  apps.fnd_responsibility_tl.responsibility_name%TYPE;
BEGIN
   FOR c IN c_responsibilities(p_search_criteria)
   LOOP
      BEGIN
         SELECT   r.responsibility_name
         INTO     lv_temp
         FROM     apps.fnd_responsibility_tl r
         WHERE    r.responsibility_name = c.search_responsibility;

         dbms_output.put_line(c.search_responsibility || ' EXISTS');
      EXCEPTION 
         WHEN no_data_found THEN
            dbms_output.put_line(c.search_responsibility || ' ERROR');
      END;
   END LOOP;  
END;