1

好的,我已经在 oracle 中编写了一个基本函数,用于根据客户端 id 和指定的日期返回当前工作人员。

它按预期工作。

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

会返回类似:

客户1 | 一位工人

但是,我想知道是否可以要求该函数从许多不同的工作人员类型中返回最新的工作人员。

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

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

它会返回:

客户1 | 经理

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

谢谢。

4

1 回答 1

2

快速而肮脏的解决方案#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
于 2013-07-16T16:23:49.660 回答