PLSQL根据输入添加特定列

时间:2016-09-14 12:24:18

标签: plsql

我的表看起来像

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)

CREATE OR REPLACE FUNCTION MY_FUNCTION (P_INPUT_01   IN NUMBER,
                                        P_INPUT_02   IN NUMBER)
   RETURN NUMBER
AS
   V_RESULT   NUMBER := 0;
BEGIN
   SELECT (CASE
              WHEN P_INPUT_01 = 1 AND P_INPUT_02 = 3 THEN DAY1 + DAY2 + DAY3
              WHEN P_INPUT_01 = 2 AND P_INPUT_02 = 3 THEN DAY2 + DAY3
              ELSE NULL -- WARNING: NULL IN ANY OTHER CASE!!
           END)
     INTO V_RESULT
     FROM MY_TABLE
    WHERE STARTDAY = P_INPUT_01 AND ENDDAY = P_INPUT_02;

   RETURN V_RESULT;
END MY_FUNCTION;

用法示例:

SELECT my_function (2, 3) FROM DUAL;

结果:1​​7

========================

为了准备环境,我已经使用了这些陈述:

CREATE TABLE my_table
(
   startday   NUMBER,
   endday     NUMBER,
   day1       NUMBER,
   day2       NUMBER,
   day3       NUMBER,
   day4       NUMBER
);

INSERT INTO my_table
    VALUES (1,
            4,
            2,
            3,
            5,
            3);

INSERT INTO my_table
    VALUES (3,
            4,
            3,
            5,
            1,
            6);

INSERT INTO my_table
    VALUES (2,
            3,
            3,
            7,
            10,
            9);

COMMIT;