IF (EXISTS(Select * from sys.sysprocedure where LCase(proc_name) = LCase('CalcNotPayedSaleSumDiscount')))
THEN Drop procedure CalcNotPayedSaleSumDiscount
END IF

GO

create function DBA.CalcNotPayedSaleSumDiscount( in @SaleId integer ) 
returns numeric(12,4)
begin
  declare @res numeric(12,4);
  set @res = (select round(SUM((RegQty-PayedQty)*(SL.SellPrice*(-Sl.Discount/100))),2)
      from SaleOrderLines as SL
      where SL.DocId = @SaleId);
  return(@res)
end