if exists (SELECT NAME FROM sysobjects s WHERE s.name='fGetMablaghFactor') begin drop function fGetMablaghFactor end go create function fGetMablaghFactor(@code int , @noe smallint) returns decimal(19,4) as begin declare @t decimal(19,4); if (@noe = 28 or @noe = 32) -- Foroosh Ya BargashtAzKharid begin set @t= isnull( ( select sum( (d.mablagh*d.meghdar1*d.meghdar2*d.tedad)+ (case when d.CodeArzeshAfzoodeh is not null then isnull(MablaghArzeshAfzoodeh,0) else 0 end)- (case when d.codeTakhfif is not null then isnull(MablagheTakhfif,0) else 0 end) ) from bargeh m,bargehDetail d where m.code = d.codebargeh and m.code = @code and m.vaziat<>101 and m.noe = @noe ) ,0); set @t = @t - isnull((select sum(mablagh) from daryaftPardakht d,bargeh b where d.codeBargehParent = b.code and b.code = @code and d.vaziat <> 101 and d.noeMaster = 40 and -- hazineh b.noe = @noe ),0); set @t = @t + isnull((select sum(mablagh) from daryaftPardakht d,bargeh b where d.codeBargehParent = b.code and b.code = @code and d.vaziat <> 101 and d.noeMaster = 42 and -- khadamat b.noe = @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.codeTakhfif is not null then isnull(MablagheTakhfif,0) else 0 end) ) from bargeh m , bargehDetail d where m.code = d.codeBargeh and m.noe = 31 and --kharid m.code = @code and m.vaziat<>101 ) ,0); set @t=@t+isnull((select sum(mablagh) from daryaftPardakht d,bargeh b where d.codeBargehParent = b.code and b.code = @code and d.vaziat<>101 and d.noeMaster = 40 and -- hazineh b.noe = 31 -- kharid ),0); set @t=@t-isnull((select sum(mablagh) from daryaftPardakht d , bargeh b where d.codeBargehParent = b.code and b.code = @code and d.vaziat<> 101 and d.noeMaster =42 and -- khadamat b.noe = 31 -- kharid ),0); end return @t end