IF (EXISTS(Select * from sys.sysprocedure where LCase(proc_name) = LCase('GetPayTypePayedRentForMonth'))) THEN Drop procedure GetPayTypePayedRentForMonth END IF GO create function DBA.GetPayTypePayedRentForMonth(in @RegNo integer) returns integer begin declare @SpravkaDate date; declare @DiffMonths integer; declare @BookRegDate date; declare @ResultDate date; declare @PayType integer; select DateRegDt into @BookRegDate from Book where RegNum = @RegNo; set @SpravkaDate="date"('1.' || bvrSpravkaM || '.' || bvrSpravkaY); set @DiffMonths=datediff(month,@BookRegDate,@SpravkaDate); set @ResultDate=null; for f as curs scroll cursor for select Inv.InvoiceNo as @InvoiceNo, Inv.InvoiceDateDt as @InvoiceDateDt, Inv.PayHow as @PayHow from Invoices as Inv,Articles as A where A.InvoiceNo = Inv.InvoiceNo and A.RegNo = @RegNo and Inv.CancelInvoiceNo = 0 order by Inv.InvoiceNo asc do if(@DiffMonths = 0) then set @PayType=@PayHow end if; set @DiffMonths=@DiffMonths-1 end for; return(@PayType) end