日期:2014-05-17  浏览次数:20803 次

sql 函数的运用问题 求解
SQL code

create or replace 
FUNCTION get_maxmissreason (param1 IN VARCHAR)
    return NUMBER
AS
    v_missreason number;
    --v_max_updatetime date;
    --v_orderno varchar2(20);
    CURSOR c_max_updatetime IS
        select  a.orderno µ¥ºÅ,max(b.updatetime) ·þÎñÐÐΪ¸üÐÂʱ¼ä 
            from servicerepair a,serviceaction b,a1report c
        where a.orderno = b.orderno
        and a.orderno = c.orderno
        group by a.orderno;
BEGIN    
    FOR r_max_updatetime IN c_max_updatetime
    LOOP
        --v_max_updatetime := r_max_updatetime.·þÎñÐÐΪ¸üÐÂʱ¼ä;
        --v_orderno := r_max_updatetime.µ¥ºÅ;
        select missreason 
            into v_missreason
        from serviceaction
        where orderno = r_max_updatetime.µ¥ºÅ 
            and updatetime = r_max_updatetime.·þÎñÐÐΪ¸üÐÂʱ¼ä;
        return v_missreason;
    END LOOP;
END;



查询代码

select a.orderno,get_maxmissreason(a.orderno) from servicerepair a,a1report b
where a.orderno = b.orderno

表1 a1report
orderno
1
2
3
4
5

表二servicerepair
orderno 
1
2
3
4
5
6
7
表三serviceaction
orderno updatetime missreason
1 时间1(dat类型) 1  
1 2
2 3  
2 4
3 5
3 6
4 7
4 8
5 9
5 10 
5 11


为什么通过上面的函数执行以后 返回的missreason都是同一个值呢?
把上面的函数改写为过程以后 就显示正确 纠结坏了!

------解决方案--------------------
运行不是同一个值就怪了

你这写的函数不关接收什么值都会执行一遍,param1 这个接收一个值就执行下面的语句一遍,你的表数据不变当然都是相同的值

BEGIN
FOR r_max_updatetime IN c_max_updatetime
LOOP
--v_max_updatetime := r_max_updatetime.·þÎñÐÐΪ¸üÐÂʱ¼ä;
--v_orderno := r_max_updatetime.µ¥ºÅ;
select missreason 
into v_missreason
from serviceaction
where orderno = r_max_updatetime.µ¥ºÅ 
and updatetime = r_max_updatetime.·þÎñÐÐΪ¸üÐÂʱ¼ä;
return v_missreason;
END LOOP;
END;
------解决方案--------------------
探讨
SQL code

create or replace
FUNCTION get_maxmissreason (param1 IN VARCHAR)
return NUMBER
AS
v_missreason number;
--v_max_updatetime date;
--v_orderno varchar2(20);
CURSOR c_max_u……