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

GO

create function DBA.CalcSaleInvoiceSumDiscount( in @InvoiceNo integer ) 
returns numeric(12,4)
begin
  declare @res numeric(12,4);
  set @res = (select round(SUM(A.Qty*(SL.SellPrice*(-Sl.Discount/100))),2)
      from SaleOrderLines_Articles as SA join SaleOrderLines as SL on SA.SaleLineID = SL.ID
        join Articles as A on A.InvoiceNo = SA.InvoiceNo and A.ArticleNo = SA.ArticleNo
      where SA.InvoiceNo = @InvoiceNo);
  return(@res)
end