MS Access rst.MoveNext not Moving to next record - vba

I am using the code below to run through a table of payments and apply those payments to available balances. I keep having trouble where it will not move to the next payment.
Sometimes it will loop through payments, most times it will try to run the same payment again which causes an error since the payment is already used.
Public Sub applyPaymentsFunction(ByVal PaymentDate As String)
Dim dbs As Database
Dim rst As DAO.Recordset
Dim qry As String
Dim printedList As DAO.Recordset
Set dbs = CurrentDb
Set printedList = dbs.OpenRecordset("000AppliedPayments")
qry = "SELECT * FROM ReceivePayment WHERE (UnusedPayment > 0) AND TxnDate = #" + PaymentDate + "#"
Set rst = CurrentDb.OpenRecordset(qry)
If rst.RecordCount > 0 Then
rst.MoveFirst
Do
Debug.Print (rst("TxnID"))
printedList.AddNew
printedList!accountNumber = rst("CustomerRefFullName")
printedList!Date = rst("TxnDate")
printedList!Payment = rst("TotalAmount")
printedList!AmountLeft = rst("UnusedPayment")
printedList.Update
Call applyPaymentsFunction2(rst("CustomerRefListID"), rst("TxnId"), rst("UnusedPayment"))
rst.MoveNext
Loop Until rst.EOF = True
rst.Close
End If
End Sub
Public Sub applyPaymentsFunction2(ByVal CustomerRefListID As String, ByVal PaymentTxnID As String, ByVal thisPayment As Integer)
Dim dbs As Database
Dim custrst As DAO.Recordset
Dim getCharges As String
Dim availPayment As Integer
Set dbs = CurrentDb
availPayment = thisPayment
getCharges = "SELECT TxnDate, TxnID, BalanceRemaining, Desc AS thisThing FROM Charge WHERE (CustomerRefListID = '" + CustomerRefListID + "'"
getInvoices = "SELECT TxnDate, TxnID, BalanceRemaining, InvoiceLineDesc as thisThing FROM InvoiceLine WHERE (CustomerRefListID = '" + CustomerRefListID + "'"
getCust = "SELECT * FROM Customer Where ParentRefListID = '" + CustomerRefListID + "'"
Set custrst = CurrentDb.OpenRecordset(getCust)
If custrst.RecordCount > 0 Then
custrst.MoveFirst
Do
getCharges = getCharges + " OR CustomerRefListID = '" + custrst("ListId") + "'"
getInvoices = getInvoices + " OR CustomerRefListID = '" + custrst("ListId") + "'"
custrst.MoveNext
Loop Until custrst.EOF = True
custrst.Close
End If
getCharges = getCharges + ") AND (BalanceRemaining > 0)"
getInvoices = getInvoices + ") AND (BalanceRemaining > 0)"
joinedChargeInvoice = getCharges + "UNION ALL " + getInvoices + "ORDER BY TxnDate ASC"
Set chargesrst = CurrentDb.OpenRecordset(joinedChargeInvoice)
If chargesrst.RecordCount > 0 Then
chargesrst.MoveFirst
Do
If availPayment = 0 Then
Exit Sub
ElseIf availPayment = chargesrst("BalanceRemaining") Then
Debug.Print ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(availPayment, "0.00") + " )")
DoCmd.RunSQL ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(availPayment, "0.00") + " )")
availPayment = 0
Exit Sub
ElseIf availPayment < chargesrst("BalanceRemaining") Then
Debug.Print ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(availPayment, "0.00") + " )")
DoCmd.RunSQL ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(availPayment, "0.00") + " )")
availPayment = 0
Exit Sub
ElseIf availPayment > chargesrst("BalanceRemaining") Then
Debug.Print ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(chargesrst("BalanceRemaining"), "0.00") + " )")
DoCmd.RunSQL ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(chargesrst("BalanceRemaining"), "0.00") + " )")
availPayment = availPayment - chargesrst("BalanceRemaining")
End If
chargesrst.MoveNext
Loop Until chargesrst.EOF = True Or availPayment = 0
chargesrst.Close
End If
End Sub
i have tried rst.MoveNext and rst.Move(1)
i have tried with and without the Exit Sub
i have tried 1 big query, and broken up into these two where it calls a separate sub

I am pretty sure that the problem lies in the Exit Sub statements in your secondary subroutine. When you hit these, you are not closing the open recordset chargerst.
Admittedly it is a very long time since I programmed DAO in VBA, but I am sure there is a problem if you exit a subroutine leaving a recordset open and returning to a main routine. Please try always closing the chargerst recordset before calling Exit Sub

Related

Access dynamic filtering listbox with double where clause

I've got a dynamic textbox filtering function in VBA
Dim sSQL As String
sSQL = "SELECT qry_allUtilities.ID, qry_allUtilities.Supplier AS Lieferant, qry_allUtilities.Cabinet AS Ablageort, qry_allUtilities.Size AS Grösse, qry_allUtilities.WorkingLength AS Nutzlänge, qry_allUtilities.Description AS Bezeichnung "
sSQL = sSQL & " FROM qry_allUtilities "
If Not sFilter = "" Then
Dim arrFilter
arrFilter = Split(sFilter, "+")
Dim varWort
For Each varWort In arrFilter
If Not varWort = "" Then
Dim sWort As String
sWort = varWort
sSQL = sSQL & " AND [ID] & ' ' & [Supplier] & ' ' & [Floor] & ' ' & [Cabinet] & ' ' & [Size] & ' ' & [WorkingLength] LIKE '*" & sWort & "*'"
End If
Next
sSQL = Replace(sSQL, " AND ", " WHERE ", 1, 1, vbTextCompare)
End If
ctlListe.RowSource = sSQL
and would like to extend this with another WHERE clause because I have to exclude the records with qry_allUtilities.InActive=False
How do I do this? I always keep getting null or it won't exclude the records with InActive=True :/
I usually do this to add a variable (but unknown) number of filter options:
strFilter = "" ' build the filter string in here
if <first condition reason is true> then
strFilter = strFilter + first condition + " AND "
end if
if <second condition reason is true> then
strFilter = strFilter + <second condition> + " AND "
end if
' finish up
if len(strFilter) > 0 then ' some critera are valid
strFilter = Left(strFilter, Len(strFilter) - 5) ' chop off the spare " AND "
strFilter = " WHERE " + strFilter ' put the " WHERE " on the front
' else ' no where clause
end if
Note that the spaces either side of the " AND " and " WHERE " are important.

want to update record if exists and insert if not exists

want to update record if exists and insert if not exists into vsolv_trn_tsalesregdump Is tsalesregdump_name is unique in table vsolv_trn_tsalesregdump
when i click check box that particular row should be check on other table and how to use it for loop in form loop i can use the "tsalesdump_date,tsalesdump_name,executivename_executive" this three if the value is same its go to update and otherwise its not to same its move on insert how can i write it can any 1help me
if i have use two table one temp and other 1 is orginal\ temp table =vsolv_tmp_tsalesdump orginal table=vsolv_trn_tsalesregdump.
if already i hav save the data in orginal table,again if i hav assing data for temp table and view in radgrid if select and submit the button its go to check on orginal table if the value is already there its update it otherwise insert how can use it
Protected Sub btn_Submit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_Submit.Click
lblerrmsg.Text = ""
Dim chk As CheckBox
Dim lbtn As LinkButton
Dim Res As Long
Dim lobjrow As DataRow
Dim lObjErrTable As New DataTable
Dim a As Integer = 0
Dim dtcarbooking As New DataTable
Dim dtDumpBooking As New DataTable
Dim lsRefid As String = String.Empty
Dim dtdumpsample As New DataTable
Dim name As String = String.Empty
If Check_Validation() = True Then
Exit Sub
End If
Gobjdbconn.OpenConn()
lObjErrTable = Error_TabelFill()
For i As Integer = 0 To GVUpload.Items.Count - 1
chk = GVUpload.Items(i).FindControl("chkupload")
If chk.Checked = True Then
lsRefid = GVUpload.Items(i).GetDataKeyValue("tsalesdump_gid").ToString()
MsSql = ""
MsSql &= "Select tsalesdump_gid,tsalesdump_date,tsalesdump_name,executivename_executive,tsalesdump_vch_no,tsalesdump_debit,tsalesdump_credit"
MsSql &= " from vsolv_tmp_tsalesdump as a"
MsSql &= " left join vsolv_trn_executivename as b on a.tsalesdump_name = b.executivename_particulars"
MsSql &= " where tsalesdump_gid = '" & lsRefid & "' and tsalesdump_isremoved = 'N'"
dtDumpBooking = Gobjdbconn.GetDataTable(MsSql)
MsSql = ""
MsSql &= "Insert into vsolv_trn_tsalesregdump(tsalesregdump_date,tsalesregdump_name,tsalesregdump_executive,tsalesregdump_vch_no"
MsSql &= " ,tsalesregdump_debit,tsalesregdump_credit,tsalesregdump_importby)"
MsSql &= " Values ('" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "'"
MsSql &= ",'" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "'"
MsSql &= ",'" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "'"
MsSql &= " ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "'"
MsSql &= " ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "','" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "','SIVA')"
MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)
If MnResult = 1 Then
MsSql = ""
MsSql &= " Delete from vsolv_tmp_tsalesdump where tsalesdump_gid = '" & lsRefid & "'"
Gobjdbconn.ExecuteNonQuerySQL(MsSql)
Else
lobjrow = lObjErrTable.NewRow()
a = a + 1
lobjrow("Sno") = a
lobjrow("Booking Ref No") = dtcarbooking.Rows(0).Item("tsalesregdump_name").ToString
lobjrow("Description") = "Duplicate Record"
lObjErrTable.Rows.Add(lobjrow)
End If
End If
Next
POPSummary()
If Not lObjErrTable Is Nothing Then
If lObjErrTable.Rows.Count > 0 Then
Call Pop_Data(lObjErrTable)
End If
End If
End Sub
If you want to update record if already exists else insert in SQL then you can achieve by following: You need to change MsSql string for Insert command
MsSql = "" + _
"IF EXISTS(Select tsalesregdump_name From vsolv_trn_tsalesregdump Where tsalesregdump_name = '" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "') " + _
"BEGIN " + _
" Update vsolv_trn_tsalesregdump " + _
" Set tsalesregdump_date = '" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "' " + _
" ,tsalesregdump_executive = '" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "' " + _
" ,tsalesregdump_vch_no = '" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "' " + _
" ,tsalesregdump_debit = '" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "' " + _
" ,tsalesregdump_credit = '" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "' " + _
" ,tsalesregdump_importby = 'SIVA' " + _
" Where tsalesregdump_name = '" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "' " + _
"END " + _
"ELSE " + _
"BEGIN " + _
" Insert into vsolv_trn_tsalesregdump(tsalesregdump_date,tsalesregdump_name,tsalesregdump_executive,tsalesregdump_vch_no " + _
" ,tsalesregdump_debit,tsalesregdump_credit,tsalesregdump_importby) " + _
" Values ('" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "','" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "','SIVA') " + _
"END "
MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)
I am assuming here that tsalesregdump_name is unique.

open a query based on many choices

hello i wrote this code to open a report based on a query
and this query is based on the toggle button
the problem is if i press one toggle button all work
but if i press more than toggle button in the same time it will not give me the right records or it will give me an empty report
this is the code
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE * FROM tbl_Mouzakarat"
Dim p_7abes As String
Dim p_gharame As String
Dim p_done As String
Dim p_undone As String
Dim p_khoulasa As String
Dim p_mouzakara As String
Dim p_karar As String
Dim p_jaze2e As String
Dim p_lebanese As String
Dim p_foreign As String
Dim p_SQL_criteria As String
p_7abes = Trim(Me!text_7abes & " ")
p_gharame = Trim(Me!text_gharame & " ")
p_done = Trim(Me!text_done & " ")
p_undone = Trim(Me!text_undone & " ")
p_khoulasa = Trim(Me!text_khoulasa & " ")
p_mouzakara = Trim(Me!text_mouzakara & " ")
p_karar = Trim(Me!text_karar & " ")
p_jaze2e = Trim(Me!text_jaze2e & " ")
p_lebanese = Trim(Me!text_lebanese & " ")
p_foreign = Trim(Me!text_lebanese & " ")
If p_7abes <> "" Then
p_SQL_criteria = "[Punish]" & " LIKE '" & p_7abes & "'"
End If
If p_gharame <> "" Then
p_SQL_criteria = "[Punish]" & " LIKE '*" & p_gharame & "*'"
End If
If p_done <> "" Then
p_SQL_criteria = "[Status_Check]" & " LIKE '*" & p_done & "*'"
End If
If p_undone <> "" Then
p_SQL_criteria = "[Status_Check]" & " LIKE '*" & p_undone & "*'"
End If
If p_khoulasa <> "" Then
p_SQL_criteria = "[Type]" & " LIKE '*" & p_khoulasa & "*'"
End If
If p_mouzakara <> "" Then
p_SQL_criteria = "[Type]" & " LIKE '*" & p_mouzakara & "*'"
End If
If p_karar <> "" Then
p_SQL_criteria = "[Type]" & " LIKE '*" & p_karar & "*'"
End If
If p_jaze2e <> "" Then
p_SQL_criteria = "[Type]" & " LIKE '*" & p_jaze2e & "*'"
End If
If p_lebanese <> "" Then
p_SQL_criteria = "[Nationality]" & " LIKE '*" & p_lebanese & "*'"
End If
If p_foreign <> "" Then
p_SQL_criteria = "[Nationality]" & " NOT LIKE '*" & p_foreign & "*'"
End If
If Me.chk7abes.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkGharame.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkDone.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.ChkUndone.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkKhoulasa.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkMouzakara.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkKarar7abes.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
If Me.chkKararJaze2e.Value = True Then
DoCmd.RunSQL "INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
End If
DoCmd.OpenReport "rpt_Mouzakarat", acViewPreview
DoCmd.Close acForm, "frm_Printing"
will someone check the code please
You are overwriting p_SQL_criteria each time then running the same exact query each time no matter how many toggle buttons are pressed.
"INSERT INTO tbl_Mouzakarat select * from " & "[qry_Mouzakarat]" & " where " & p_SQL_criteria
This is always the exact same SQL statement for each of your DoCmd statements.
I'm not really sure how your toggle buttons interact with the parameters you are trying to create so it's hard to suggest solutions, but this is why your having the problem you are having.

datagridview update to database

please help me...
I load my database in the datagrid view and edit some cells.
Now I just need to update my database
here are my codes
Dim dT As DataTable = MyDB.ExecCommand("SELECT `Field Name` FROM `tblfield`", "wellsfargo").Tables(0)
Dim sSQL As String = ""
Dim dZ As DataTable = MyDB.ExecCommand("SELECT " & sColumn & " FROM `" + cboJob.Text.Trim + "`", "wellsfargo", 0).Tables(0)
dColumn = New DataTable
dColumn = MyDB.ExecCommand("SHOW COLUMNS IN tblrecord", "wellsfargo", 0).Tables(0)
If dZ.Rows.Count <> 0 Then
sSQL = "UPDATE " & sColumn & " FROM `" + cboJob.Text.Trim + "`"
MyDB.ExecQuery(sSQL, "wellsfargo")
Else
Dim sColumn As String = ""
For z As Integer = 0 To dT.Rows.Count - 1
If z = 0 Then
sColumn = "`" & dT.Rows(z).Item(0).ToString & "`"
Else
sColumn = sColumn & ",`" & dT.Rows(z).Item(0).ToString & "`"
End If
Next
sSQL = "INSERT INTO `" + MyJob + "` (" + sColumn + ") "
MyDB.ExecQuery(sSQL, "wellsfargo")
End If
Done.
I used this codes..
Try
Cursor = Cursors.WaitCursor
Dim sSQL As String
sSQL = "UPDATE `" + cboJob.Text.Trim + "` SET `Description` ='" + TextBox1.Text + "' WHERE `Description`= '" + Label2.Text + "' AND `Line Number` ='" + comList.Text + "'"
MyDB.ExecQuery(sSQL, "wellsfargo")
MsgBox("Updated!")
btnUpdate.Enabled = False
Catch ex As Exception
MsgBox("Select table first to Update")
End Try
Cursor = Cursors.Default

ASP Update database, insert if does not exist

I have a CSV I need to loop through, get the ID of each row, then loop through the database, comparing the csvID to each dbID. If the ID exists in the database, it will then update the record with relevant info from the CSV.
However, I'm stuck in an endless loop (from what I can tell) and am not sure how to get out of it.
Option Explicit
Server.ScriptTimeout = 2147483647
dim conn, rs, updatedUser, updatedDate, filePath
dim deactivateSQL, csvConn, connCSV, csv, sql
dim dbID, dbSSN, dbLast, dbFirst, dbMiddle, dbGender, dbScl, dbCls
dim csvID, csvSSN, csvLast, csvFirst, csvMiddle, csvGender
dim csvScl, csvCls, csvGrd, csvHrm
updatedUser = Request.Cookies("UserN")
updatedDate = date() & " " & time()
filePath = "\path\to\file"
' Connect to Students.CSV
csvConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &_
Server.MapPath(filePath) &_
";Extended Properties='text;HDR=no;FMT=Delimited';"
Set connCSV = Server.CreateObject("ADODB.Connection")
connCSV.Open csvConn
Set csv = Server.CreateObject("ADODB.recordset")
csv.open "SELECT * FROM Students.csv", connCSV
temp = csv.RecordCount
redim toAdd(temp)
' Begin looping through Students.csv
do until csv.eof
' Get Students.csv Column Values
' please disregard the "replace" stuff for now
csvID = replace(replace(csv.fields(0), " ", ""), "'", "")
csvSSN = replace(replace(csv.fields(1), " ", ""), "'", "")
csvLast = replace(replace(csv.fields(2), " ", ""), "'", "")
csvFirst = replace(replace(csv.fields(3), " ", ""), "'", "")
csvMiddle = replace(replace(csv.fields(4), " ", ""), "'", "")
csvGender = replace(replace(csv.fields(5), " ", ""), "'", "")
csvScl = replace(replace(csv.fields(6), " ", ""), "'", "")
csvGrd = replace(replace(csv.fields(7), " ", ""), "'", "")
csvHrm = replace(replace(csv.fields(8), " ", ""), "'", "")
' Connect to database
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "E:/path/to/file/database.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM tblStudent", conn
' Begin looping through tblStudents
do until rs.eof
' Get tblStudents.StudentID
dbID = rs.fields("StudentID")
dbSSN = rs.fields("SSN")
dbLast = rs.fields("LastName")
dbFirst = rs.fields("FirstName")
dbMiddle = rs.fields("MiddleName")
dbGender = rs.fields("Gender")
dbScl = rs.fields("School")
dbCls = rs.fields("Class")
if dbID = csvID then
' if dbID matches csvID,
' update tblStudents with the new CSV data
sql = "UPDATE tblStudent SET " &_
"Active='Yes' AND " &_
"SSN='" & csvSSN & "' AND " &_
"LastName='" & csvlast & "' AND " &_
"FirstName='" & csvFirst & "' AND " &_
"MiddleName='" & csvMiddle & "' AND " &_
"Gender='" & csvGender & "' AND " &_
"School='" & csvScl & "' AND " &_
"GradeLvl='" & csvGrd & "' AND " &_
"HomeRoomID='" & csvHrm & "' AND " &_
"PrevClass1='" & dbCls & "' AND" &_
"lastUpdatedUser='" & updatedUser & "' AND" &_
"lastUpdatedDate='" & updatedDate & "'" &_
"WHERE StudentID=" & dbID & ";"
on error resume next
conn.execute(sql)
else
' I am not sure what to do here...
' I thought about creating a dynamic array:
' adding to the array for each ID not found
' however, I am not THAT skilled.
' If someone could help me with that,
' I would be grateful
end if
rs.movenext
loop
csv.movenext
loop
' This is the INSERT SQL I need to execute,
' but do not exactly know where it needs to be placed either
sql = "INSERT INTO tblStudent (" &_
"Active, StudentID, SSN, LastName, FirstName, MiddleName, Gender, "&_
"School, GradeLvl, HomeRoomID, lastUpdatedUser, LastUpdatedDate" &_
") VALUES (" &_
"'Yes', '" & csvID & "', '" & csvSSN & "', '" & csvLast & "', '" &_
csvFirst & "', '" & csvMiddle & "', '" & csvGender & "', '" &_
csvScl & "', '" & csvGrd & "', '" & csvHrm & "', '" &_
updatedUser & "', '" & updatedDate & _
"');"
on error resume next
conn.execute(sql)
if error<>0 then
response.cookies("updated") = "no"
response.cookies("updated").Expires = dateadd("s", 2, now())
response.redirect("step-5.asp")
else
response.cookies("updated") = "yes"
response.cookies("updated").Expires = dateadd("s", 2, now())
response.redirect("step-6.asp")
end if
This may not even be the best way to go about doing this and I'm open to suggestions here, too. But, first I need to have this work: loop through the CSV, update the DB if the csvID exists in the DB and insert the csvID row info if it doesn't exist.
//Update
Thanks to Richard Benson, I've been able to get my code to work properly, for the most part: I'm hung up on this bit of code:
csvLast = replace(csv.fields(2), "'", "")
csvFirst = replace(csv.fields(3), "'", "")
if csv.fields(4) <> NULL then
csvMiddle = replace(csv.fields(4), "'", "")
else
csvMiddle = csv.fields(4)
end if
The replace() function works on the first & last name, but when I get to the middle name, it won't work. If I keep it as csvMiddle = replace(csv.fields(4), "'", "") by itself it errors out sometimes because the middle name field is sometimes empty. How can I get this to work properly? This is most likely the final problem before this code will run smoothly.
Will try and put this into more context later, for now a pointer on what I do when trying to achieve the insert if not in db, update if is.
Set rs = Server.CreateObject("ADODB.Recordset")
rs.ActiveConnection = "whateveryourconnectionstringis"
rs.Source = "SELECT * FROM Table WHERE ID = '" & intValue & ";"
rs.CursorType = 2
rs.CursorLocation = 3
rs.LockType = 3
rs.Open()
'If at this point we have no records, it doesnt exist so add it and any data all new records need'
If rs.BOF AND rs.EOF Then
rs.AddNew
rs("ID") = intValue
End If
'Update the rest of the fields
rs("Field1") = Value1
rs("Field2") = Value2
rs("Field3") = Value3
rs.Update()
rs.Close()
Set rs = Nothing
Depending on how you are looping and how many loops you will go through, this may be too intensive, but it's the simplest from a code point-of-view
The first thing I notice is that you do loop before rs.movenext. This means that rs.eof will never occur because you never move forward using rs.movenext and indeed would result in an infinite loop.
I assume this is just a typo, because you do it correctly for the outer CSV loop.
Here's what I ended up using (in case someone else runs into an issue like this):
Thanks everyone for your help.
Server.ScriptTimeout = 2147483647
Response.Buffer = False
on error resume next
dim conn1, conn, rs, updatedUser, updatedDate, filePath,
dim deactivateSQL, csvConn, connCSV, csv, sql
dim csvID, csvSSN, csvLast, csvFirst, csvMiddle
dim csvGender, csvScl, csvGrd, csvCls, dbCls
updatedUser = Request.Cookies("UserN")
updatedDate = date() & " " & time()
filePath = "\path\to\file"
' --- Connect to DZ database
set conn1=Server.CreateObject("ADODB.Connection")
conn1.Provider="Microsoft.Jet.OLEDB.4.0"
conn1.Open "E:/path/to/database.mdb"
' --- Deactivate ALL students
deactivateSQL = "UPDATE tblStudent SET Active=False " &_
"AND lastUpdatedUser='" & updatedUser & "' "&_
"AND lastUpdatedDate='" & updatedDate & "';"
conn1.execute(deactivateSQL)
conn1.close
' --- Connect to Students.CSV exported by iNOW
csvConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &_
Server.MapPath(filePath) &_
";Extended Properties='text;HDR=no;FMT=Delimited';"
Set connCSV = Server.CreateObject("ADODB.Connection")
connCSV.Open csvConn
Set csv = Server.CreateObject("ADODB.recordset")
csv.open "SELECT * FROM Students.csv", connCSV
' --- Begin looping through Students.csv
do until csv.eof
' --- Get Students.csv Column Values
csvID = csv.fields(0)
if isnull(csv.fields(1)) then
csvSSN = NULL
else
csvSSN = csv.fields(1)
end if
csvLast = replace(csv.fields(2), "'", "")
csvFirst = replace(csv.fields(3), "'", "")
' --- Using IsNull() fixed the 2nd problem
' --- I was having after updating the question
if isnull(csv.fields(4)) then
csvMiddle = csv.fields(4)
else
csvMiddle = replace(csv.fields(4), "'", "")
end if
csvGender = csv.fields(5)
csvScl = csv.fields(6)
csvGrd = csv.fields(7)
csvCls = csv.fields(8)
' --- Connect to database
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "E:/path/to/database.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM tblStudent " &_
"WHERE StudentID='" & csvID & "';", conn
if rs.bof and rs.eof then
' --- if rs.bof & rs.eof, the csvID is NOT in the table
' --- Add the new csvID to DB, we'll add the rest in
' --- the UPDATE statement below
conn.execute("INSERT INTO tblStudent (StudentID) " &_
"VALUES ('" & csvID & "');")
' --- Set to 0 since it's supposed to be a number
dbCls = 0
else
' --- Get tblStudents.Class from existing record
dbCls = rs.fields("Class")
end if
' --- UPDATE the table with the appropriate info
sql = "UPDATE tblStudent SET " &_
"Active=True, " &_
"SSN=" & csvSSN & ", " &_
"LastName='" & csvlast & "', " &_
"FirstName='" & csvFirst & "', " &_
"MiddleName='" & csvMiddle & "', " &_
"Gender='" & csvGender & "', " &_
"School=" & csvScl & ", " &_
"GradeLvl=" & csvGrd & ", " &_
"Class=" & csvCls & ", " &_
"PrevClass1='" & dbCls & "', " &_
"lastUpdatedUser='" & updatedUser & "', " &_
"lastUpdatedDate='" & updatedDate & "' " &_
"WHERE StudentID='" & csvID & "';"
conn.execute(sql)
csv.movenext
loop
if error<>0 then
response.cookies("updated") = "no"
response.cookies("updated").Expires = dateadd("s", 2, now())
response.redirect("step-5.asp")
else
response.cookies("updated") = "yes"
response.cookies("updated").Expires = dateadd("s", 2, now())
response.redirect("step-6.asp")
end if