多个输入到oracle SQL函数参数

时间:2013-07-16 15:06:51

标签: sql oracle function split

好的,我在oracle中编写了一个基本函数,根据客户端ID和指定的日期返回当前worker。

它按预期工作。

FUNCTION get_worker_new_test  (p_id IN VARCHAR2, p_date IN DATE, w_type IN
VARCHAR2)     RETURN VARCHAR2 IS

CURSOR c1 IS

 SELECT 
 O_RELATIONSHIPS.ID

 FROM o_relationships
 WHERE rel_source_per_gro_id = p_id
 AND rel_rty_code in (w_type)
 AND p_date BETWEEN rel_start_date AND NVL(rel_end_date, SYSDATE)
 ORDER BY rel_start_date DESC;


 l_name VARCHAR2(70) ;

BEGIN
OPEN c1;
FETCH c1 INTO l_name;
CLOSE c1;

RETURN l_name;

END;

例如,像这样的查询:

SELECT
CLIENT,
get_worker_new_test(CLIENT,sysdate,'WORKER')
FROM TABLE

会返回类似的内容:

Client1 |工人

但是,我想知道是否有可能要求函数从许多不同的工作者类型返回最新的worker。

例如,我会像这样编写查询:

SELECT
CLIENT,
get_worker_new_test(CLIENT,sysdate,'WORKER,CLERK,MANAGER')
FROM TABLE

它会回来:

Client1 |经理

如果分配的最新工人类型是经理。我想我需要一个将字符串分成单独条目的函数,但即便如此,我也不确定是否有更好的方法来实现它。任何建议或指导将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:1)

快速而肮脏的解决方案#1 。在函数中使用下一个查询:

SELECT 
O_RELATIONSHIPS.ID

FROM o_relationships
WHERE rel_source_per_gro_id = p_id
AND instr( ','||w_type||',', ','||rel_rty_code||',' ) <> 0 --<-- Check comma-quoted worker type to be substring of parameter string
AND p_date BETWEEN rel_start_date AND NVL(rel_end_date, SYSDATE)
ORDER BY rel_start_date DESC;

快速而肮脏的解决方案#2 。创建SQL类型:

create type uservchartab as table of varchar2(4000);

用以下代码替换您的函数:

FUNCTION get_worker_new_test  
  (p_id IN VARCHAR2, p_date IN DATE, w_type IN uservchartab)
  RETURN VARCHAR2 
IS

  CURSOR c1 IS
     SELECT O_RELATIONSHIPS.ID
       FROM o_relationships
      WHERE rel_source_per_gro_id = p_id
        AND rel_rty_code member of w_type --<-- Check worker type to be one from the condition
        AND p_date BETWEEN rel_start_date AND NVL(rel_end_date, SYSDATE)
      ORDER BY rel_start_date DESC;

  l_name VARCHAR2(70) ;

BEGIN
  OPEN c1;
  FETCH c1 INTO l_name;
  CLOSE c1;

  RETURN l_name;
END;

像这样使用:

SELECT CLIENT
     , get_worker_new_test( CLIENT, sysdate, uservchartab( 'WORKER', 'CLERK', 'MANAGER' ) )
  FROM TABLE