if exists (select name from dbo.sysobjects where name='fGetMablaghFactor') drop function fGetMablaghFactor go create function fGetMablaghFactor(@code int , @noe smallint) returns decimal(19,4) as begin declare @t decimal(19,4); if (@noe = 0 or @noe = 4) -- 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<>1 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 <> 1 and d.noeMaster = 2 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 <> 1 and d.noeMaster = 4 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 = 3 and --kharid m.code = @code and m.vaziat<>1 ) ,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<>1 and d.noeMaster = 2 and -- hazineh b.noe = 3 -- 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<>1 and d.noeMaster =4 and -- khadamat b.noe = 3 -- kharid ),0); end return @t end go