pl / sql create函数,用于根据条件添加特定列

时间:2016-02-12 04:42:42

标签: sql plsqldeveloper

我的表看起来像

startday endday day1 day2 day3 day4
1        4      2    3    5    3      
3        4      3    5    1    6    
2        3      3    7   10    9

该函数的输入应该是startday和endday。

如果输入为1和3,则输出应为day1+day2+day3

如果输入为2和3,则输出应为day2+day3

任何人都可以帮助我...

1 个答案:

答案 0 :(得分:0)

为什么要使用功能?这可以通过简单查询来实现:

SELECT CASE
     WHEN startday = 1 AND endday = 3 THEN
       day1 + day2 + day3
     WHEN startday = 2 AND endday = 3 THEN
       day2 + day3
   END as result
FROM table1
WHERE startday = YOUR_PARAM and endday = YOUR_PARAM

如果您startdayendday是唯一的,那么功能就会起作用。然后可以编写函数:

CREATE FUNCTION func(
  i_startday  INTEGER
, i_endday    INTEGER)
RETURN INTEGER
IS
  l_result INTEGER;
BEGIN
  SELECT CASE
         WHEN startday = 1 AND endday = 3 THEN
           day1 + day2 + day3
         WHEN startday = 2 AND endday = 3 THEN
           day2 + day3
       END
  INTO l_result
  FROM table1
  WHERE startday = i_startday
    AND endday = i_endday
    AND ROWNUM = 1; -- rownum = 1 because I don't know unique of fields

  RETURN l_result;
END;