IF (EXISTS(Select * from sys.sysprocedure where LCase(proc_name) = LCase('CalcNotPayedSaleGrandTotal'))) THEN Drop procedure CalcNotPayedSaleGrandTotal END IF GO create function DBA.CalcNotPayedSaleGrandTotal( in @SaleId integer ) returns numeric(12,4) begin declare @res numeric(12,4); set @res = (select round(SUM((RegQty-PayedQty)*(SL.SellPrice*(1+Sl.Discount/100))),2) from SaleOrderLines as SL where SL.DocId = @SaleId); return(@res) end