2011-05-10 127 views
0

我將我的後續plsql函數從oracle遷移到mssql 2008中,但不知道如何在while循環中將光標轉換。請你幫忙嗎?將光標從PLSQL轉換爲TSQL

CREATE OR REPLACE function f_genel_iskonto (p_ID_MUSTERI_SIRKET in number, p_BILGI_TIP in NUMBER) 
return number 
is 
v_iskonto number; 
begin 
v_iskonto:=null; 
for c in (
    SELECT an.mt_iskonto_oran, an.aktif, an.id_anlasma 
    FROM lu_anlasma an 
    WHERE an.id_musteri_sirket = p_ID_MUSTERI_SIRKET AND an.id_durum = 9 
    AND (TRUNC (SYSDATE) BETWEEN an.baslangic AND an.bitis) 
ORDER BY an.baslangic DESC 
) loop 
    if p_BILGI_TIP=1 then 
     v_iskonto:=c.mt_iskonto_oran; 
    end if; 
    if p_BILGI_TIP=2 then 
     v_iskonto:=c.aktif; 
    end if; 
    if p_BILGI_TIP=3 then 
     v_iskonto:=c.id_anlasma; 
    end if; 
    exit; 
end loop; 
return v_iskonto; 
exception 
when others then 
return null; 
end; 

回答

2

在這種情況下,您不必轉換遊標/循環,因爲它只查看第一條記錄。

create function f_genel_iskonto (@p_ID_MUSTERI_SIRKET int, @p_BILGI_TIP int) 
returns int 
as 
begin 
    declare @result int 

    SELECT top 1 
     @result = case @p_BILGI_TIP 
      when 1 then an.mt_iskonto_oran 
      when 2 then an.aktif 
      when 3 then an.id_anlasma 
     end 
     FROM lu_anlasma an  
    WHERE an.id_musteri_sirket = @p_ID_MUSTERI_SIRKET AND an.id_durum = 9 
     AND (current_timestamp BETWEEN an.baslangic AND an.bitis) 
    ORDER BY an.baslangic DESC 
    return @result 
end 

而你可能需要調整日期比較來做你想做的事情。

+0

+1不使用遊標 – Leons 2011-05-11 01:16:43