if exists (SELECT NAME FROM sysobjects s WHERE s.name='fGetMablaghFactor') begin drop function fGetMablaghFactor end go create function fGetMablaghFactor(@Bar_ID int , @Dom_ID_Noe smallint) returns decimal(19,4) as begin declare @t decimal(19,4); if (@Dom_ID_Noe = 28 or @Dom_ID_Noe = 32) -- Foroosh Ya BargashtAzKharid begin set @t= isnull( ( select sum( (d.mablagh*d.meghdar1*d.meghdar2*d.tedad)+ (case when d.Taf_ID_ArzeshAfzoodeh is not null then isnull(MablaghArzeshAfzoodeh,0) else 0 end)- (case when d.Taf_ID_Takhfif is not null then isnull(MablagheTakhfif,0) else 0 end) ) from bargeh m,bargehDetail d where m.ID = d.Bar_ID and m.ID = @Bar_ID and m.dom_ID_vaziat<>101 and m.dom_ID_noe = @Dom_ID_Noe ) ,0); set @t = @t - isnull((select sum(mablagh) from daryaftPardakht d,bargeh b where d.Bar_ID = b.ID and b.ID = @Bar_ID and d.dom_ID_vaziat <> 101 and d.dom_ID_noeMaster = 40 and -- hazineh b.dom_ID_noe = @Dom_ID_Noe ),0); set @t = @t + isnull((select sum(mablagh) from daryaftPardakht d,bargeh b where d.Bar_ID = b.ID and b.ID = @Bar_ID and d.dom_ID_vaziat <> 101 and d.dom_ID_noeMaster = 42 and -- khadamat b.dom_ID_noe = @Dom_ID_Noe ),0); end else begin set @t= isnull( ( select sum( (d.mablagh*d.meghdar1*d.meghdar2*d.tedad)- --(case when d.IsKala=0 then isnull(d.MablaghTakhsisKhadamat,0) else 0 end)- (case when d.Taf_ID_Takhfif is not null then isnull(MablagheTakhfif,0) else 0 end) ) from bargeh m , bargehDetail d where m.ID = d.Bar_ID and m.dom_ID_noe = 31 and --kharid m.ID = @Bar_ID and m.dom_ID_vaziat<>101 ) ,0); set @t=@t+isnull((select sum(mablagh) from daryaftPardakht d,bargeh b where d.Bar_ID = b.ID and b.ID = @Bar_ID and d.dom_ID_vaziat<>101 and d.dom_ID_noeMaster = 40 and -- hazineh b.dom_ID_noe = 31 -- kharid ),0); set @t=@t-isnull((select sum(mablagh) from daryaftPardakht d , bargeh b where d.Bar_ID = b.ID and b.ID = @Bar_ID and d.dom_ID_vaziat<> 101 and d.dom_ID_noeMaster =42 and -- khadamat b.dom_ID_noe = 31 -- kharid ),0); end return @t end