将光标从PL SQL转换为SQL

时间:2011-05-10 12:48:01

标签: sql-server tsql plsql

我将以下plsql函数从oracle迁移到mssql 2008但不知道如何在while循环中转换游标。你能帮忙吗?

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;

1 个答案:

答案 0 :(得分: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

你可能需要调整日期比较来做你想做的事。