I have a table with 3000 records, and using every single one of them, I have to generate around 200 records (600k records in total), and insert them in a second table through SQL Server 2012.
I tried doing this using VBA (Selecting data from first table, calculating, and then inserting in second table), but the insertion is too slow, and takes forever. Someone suggested that I do the calculations/insertion directly in SQL, and that's what I'm trying to do, but I'm not very familiar with the language.
Here's the VBA code basically :
SQLStr = "SELECT * FROM TABLE_PRETS"
Set rs = cn.Execute(SQLStr)
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
Do Until rs.EOF = True
loanID = rs!N_CONTRAT
remainingBalance = rs!MONTANT_CREDIT
interestRate = rs!TAUX_ACTUEL / 100
insuranceRate = rs!TAUX_ASSURANCE
taxRate = rs!TVA
startDate = rs!DATE_DEBUT
monthlyRate = (interestRate * (1 + taxRate) + insuranceRate) / 12
For i = 1 To rs!DUREE
startingBalance = Round(remainingBalance, 2)
principal = Round(rs!MENSUALITE - startingBalance * monthlyRate, 2)
interestPaymentBT = Round(startingBalance * interestRate / 12, 2)
taxOnInterest = Round(interestPaymentBT * taxRate, 2)
insurancePayment = Round(startingBalance * insuranceRate, 2)
remainingBalance = Round(startingBalance - principal, 2)
SQLStr = "INSERT INTO TABLE_AMORTISSEMENT (N_CONTRAT,MOIS,DATE_ECHEANCE,MENSUALITE,SOLDE_DEPART,CAPITAL_AMORTI," _
& "INTERET_HT,TVA,ASSURANCE,CAPITAL_RESTANT)" _
& "VALUES (" & loanID & ", " & i & ", '" & DateAdd("m", i, startDate) & "', " & Replace(rs!MENSUALITE, ",", ".") & ", " _
& Replace(startingBalance, ",", ".") & ", " & Replace(principal, ",", ".") & ", " & Replace(interestPaymentBT, ",", ".") _
& ", " & Replace(taxOnInterest, ",", ".") & ", " & Replace(insurancePayment, ",", ".") & ", " _
& Replace(remainingBalance, ",", ".") & ");"
Set rs2 = cn.Execute(SQLStr, , adExecuteNoRecords)
Next i
rs.MoveNext
Loop
End if
Here's where I got so far in SQL, but I'm pretty stuck :
DECLARE contracts_cursor CURSOR FOR
SELECT N_CONTRAT, DATE_DEBUT, DUREE, MONTANT_CREDIT, TAUX_ACTUEL / 100 AS TAUX_CREDIT, TAUX_ASSURANCE, TVA, (TAUX_ACTUEL / 100 * (1 + TVA) + TAUX_ASSURANCE) / 12 AS TAUX_MENSUEL
FROM TABLE_PRETS
DECLARE @index INT, @startingBalance FLOAT, @principal FLOAT, @interestPaymentBT FLOAT, @taxOnInterest FLOAT, @insurancePayment FLOAT, @remainingBalance FLOAT
SET @index = 0;
OPEN contracts_cursor;
FETCH NEXT FROM contracts_cursor;
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM contracts_cursor;
--My brain stops working here
END;
CLOSE contracts_cursor;
DEALLOCATE contracts_cursor;
GO
The problem is, I don't know if SQL can calculate a whole column at once (like Matlab) or if I have to loop through values in a column.
Exemple of result from first table data (84 rows actually) :