2015-11-30 44 views
0

即時通訊在創建函數時遇到困難..PL/SQL在日期之間返回數據的函數

我想要函數查找某個帳戶在特定日期的租金。

功能需要兩個參數rentacc(數量)和rentdate(VARCHAR2)

create or replace function get_rent(rentacc in number,rentdate in varchar2) 
return number 
as 
atype number :=rentacc 
begin 
if atype =1 
then 
select "RATE" from "RENTCHANGE" where TO_DATE(rentdate, 'YYYY-MM-DD') >= TIME or TO_DATE(rentdate, 'YYYY-MM-DD') <=TIME; 
else return -1; 
end if; 
end get_rent; 

這是我的表rentchange

ID   ACOUNT  RATE  TIME  
---------- ---------- ---------- ---------- 
     123   1  ,58 2013-07-09 
     124   1  ,69 2013-09-02 
     125   1  1,78 2013-10-07 
     126   1  2,7 2013-10-17 

select function_name(1,20131010) 
from dual; 

將返回

function_name 
------------------------- 
1,78 

如果有人有任何建議,我將不勝感激。 謝謝。

+0

你確定這個功能是列出的嗎? – BigMike

+0

不知道我是否遵循 – Erskan

回答

0

這可能是你需要的,比以前的帖子更簡單一點!

create or replace function get_ränta(
p_kontotyp in number, 
p_datum in varchar2) 
return number 
is 
v_svar number(5,2); 
begin 


select ränta into v_svar 
from ränteändring 
where tid = (select max(tid) from ränteändring 
      where tid <= to_date(p_datum, 'yyyy,mm,dd') 
      and ktyp = p_kontotyp); 

return v_svar; 
exception 
when no_data_found then 
return -1; 
end; 
+0

哇!非常好。做得好 – Erskan

2

你的問題是混亂的,因爲你的榜樣的數據和功能使用不同的列名等

不管怎麼說,這是一個SQL語句,應該幫助你看你怎麼可能修改查詢在你的函數:

with rentchange as (select 123 id, 1 account, .58 rate, to_date('09/07/2013', 'dd/mm/yyyy') time from dual union all 
        select 124 id, 1 account, .69 rate, to_date('02/09/2013', 'dd/mm/yyyy') time from dual union all 
        select 125 id, 1 account, 1.78 rate, to_date('07/10/2013', 'dd/mm/yyyy') time from dual union all 
        select 126 id, 1 account, 2.7 rate, to_date('17/10/2013', 'dd/mm/yyyy') time from dual) 
-- end of mimicking the rentchange table with data in it. See SQL below: 
select rate 
from (select id, 
       account, 
       rate, 
       time start_time, 
       lead(time, 1, sysdate) over (partition by account 
              order by time) end_time 
     from rentchange) 
where start_time <= to_date('10/10/2013', 'dd/mm/yyyy') 
and end_time > to_date('10/10/2013', 'dd/mm/yyyy'); 

     RATE 
---------- 
     1.78 

這使用lead()分析函數來獲取有關下一行日期的信息(或者,如果沒有下一行,請使用當前時間),然後給出您可以在其中查詢的日期範圍。

+0

但是,如果我想插入100多行到我的表中,我必須改變我的功能。這不是可選的嗎? – Erskan

+0

@ErikRehn如果您正在討論我用來生成數據以運行sql主要位的rentchange子查詢,那麼我希望您意識到您不需要它。由於你沒有充分解釋你的功能應該做什麼以及如何使用,所以幾乎不可能說你是否需要改變它。我會爭辯說,如果你只是選擇一個特定的帳戶,那麼你可能沒有把它設計得很好! – Boneist

+0

所以你聲明開始和停止時間我會改用我的參數? – Erskan

相關問題