根据输入返回不同列值的函数

时间:2019-07-19 14:52:18

标签: sql oracle plsql

这是表格水果-

FILTER  A   B   C
Apple   0   3   6
Orange  1   4   7
Apricot 2   5   8

是否可以创建一个函数来为苹果(0)返回A列,为橙子(4)返回B列,为杏(8)返回C列?

SELECT Fruit_Function('Apple') FROM dual; --RESULT 0.
SELECT Fruit_Function('Orange') FROM dual; --RESULT 4.
SELECT Fruit_Function('Apricot') FROM dual; --RESULT 8.

现在我有这样的功能

CREATE OR REPLACE FUNCTION Fruit_Function (v_id integer, v_filter varchar2)
RETURN varchar2 as

    v_rp varchar2(500);

BEGIN
    SELECT ASSIGNEE INTO v_rp
    FROM FRUITS a
    WHERE a.id = v_id AND a.filter = v_filter;

    RETURN v_rp;
END Fruit_Function;

此函数返回列名,但不返回实际值。

5 个答案:

答案 0 :(得分:2)

创建视图!

create view v_t as
    select t.*,
           (case when filter = 'Apple' then a
                 when filter = 'Orange' then b
                 when filter = 'Apricot' then C 
           end) as result
    from t;

然后,使用视图查看包中的查询。

您还可以将列作为计算列直接添加到表中:

alter table t add result number generated always as
           (case when filter = 'Apple' then a
                 when filter = 'Orange' then b
                 when filter = 'Apricot' then C 
            end);

采用这种方法,该列看起来像是表的一部分。

答案 1 :(得分:0)

您可以使用case表达式

SELECT
    CASE filter WHEN 'Apple' THEN A WHEN 'Orange' THEN B WHEN 'Apricot' THEN C END AS result
FROM
    myTable

如果要重复使用100次以上,请从中创建一个视图并输出所有其他列

CREATE OR REPLACE VIEW myTableEx
   SELECT
      CASE filter WHEN 'Apple' THEN A WHEN 'Orange' THEN B WHEN 'Apricot' THEN C END AS result,
      filter, A, B, C, ...
   FROM
      myTable;

答案 2 :(得分:0)

您可以在函数中使用以下逻辑

Function(input)
Begin
If(input =='Apple')
Select A from table name
Else if(input =='something')
Select B from table name
....

答案 3 :(得分:0)

创建一个带有2个输入参数的函数,称为filter_value,col_value

对于函数定义,

  1. 定义一个名为v_result的变量
  2. 选择
  3. 立即执行“选择” || col_value || ‘from your_table where filter =‘’’|| filter_value || ‘’’进入v_result;
  4. 返回v结果;

答案 4 :(得分:-1)

您可以使用此:

DECLARE @A TABLE
(ILTER varchar(20),  A int,   B int,  C int)
insert into @A
values 
('Apple',   0  , 3 ,  6), 
('Orange',  1 ,  4  , 7), 
('Apricot', 2,   5 ,  8) 

DECLARE @ilter varchar(20) = 'Orange' 
DECLARE @column int = 4 


SELECT CASE WHEN @ilter = 'Apple' and @column = 0 THEN  A  
            WHEN @ilter = 'Orange' and @column = 4 THEN B
            WHEN @ilter = 'Apricot' and @column = 8 THEN C 
       END Result FROM @A