DROP TABLE cursor_results DECLARE @cod_contr_old FLOAT,@cod_contr_n FLOAT, @paym_date_crt AS SMALLDATETIME, @paym_date_old AS SMALLDATETIME --, @amount_to_pay AS float DECLARE interest_cursor CURSOR FOR SELECT RiskRep..contracts.cod_contract, RiskRep..reimbursement_plan.payment_date ---RiskRep..reimbursement_plan.amount_to_pay --no_days = @paym_date2 - @paym_date1 FROM RiskRep..reimbursement_plan INNER JOIN RiskRep..contracts ON RiskRep..contracts.cod_contract = RiskRep..reimbursement_plan.cod_contract WHERE RiskRep..reimbursement_plan.cod_payment = 'I' AND RiskRep..contracts.int_rate_descrip <>'FIXED' ORDER BY RiskRep..reimbursement_plan.cod_contract,RiskRep..reimbursement_plan.payment_date --FOR UPDATE OF amount_to_pay OPEN interest_cursor FETCH NEXT FROM interest_cursor INTO @cod_contr_n, @paym_date_crt SET @paym_date_old = 0 SET @cod_contr_old = 0 CREATE TABLE cursor_results(cod_contract VARCHAR(10),paym_date_o SMALLDATETIME,paym_date_c SMALLDATETIME,no_days numeric(10,0)) --WHILE CURSOR_STATUS('global','interest_cursor') = 1 WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM interest_cursor INTO @cod_contr_n,@paym_date_crt INSERT INTO cursor_results(cod_contract,paym_date_o, paym_date_c, no_days) VALUES( @cod_contr_n, @paym_date_old, @paym_date_crt, CASE WHEN @paym_date_old<>0 THEN DATEDIFF(d,@paym_date_old,@paym_date_crt) ELSE 0 END ) IF @paym_date_crt>=0 SET @paym_date_old = @paym_date_crt IF @cod_contr_old <> @cod_contr_n begin SET @paym_date_old = 0 SET @cod_contr_old=@cod_contr_n end END CLOSE interest_cursor DEALLOCATE interest_cursor SELECT * FROM cursor_results ORDER BY cursor_results.cod_contract