ASP Update database, insert if does not exist - sql

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

Related

UPDATE Query in MS Access using SQL in VBA with declared strings

been a while since I've posted so please forgive any formatting issues. Looking to update a table field with a value from another record in the same field in the same table.
I've declared two strings, and the strDeal string is coming back with the correct values when debugging. However when I introduce the string into the sql statement I can't the query to update the field. I'm not sure exactly what isn't working correctly, so any help would be appreciated.
The basics are I'm trying to update the Case_Qty field with a value from the same field in the same table based on the returned value from a subquery. Thanks!
Dim strDeal As String
Dim strSQL As String
strDeal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = Forms!frmStructNoDASetup!Structure_Name AND [FG_Ind] = 0 AND [Deal_No] < Forms!frmStructNoDASetup!Deal_No")
strSQL = "UPDATE tblStructuresNoDAworking SET tblStructuresNoDAworking.Case_Qty = (SELECT [Case_Qty] FROM tblStructuresNoDAworking WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & strDeal & "') WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & Me.Deal_No.Value & "'"
DoCmd.RunSQL (strSQL)
Try this where you concatenate the values from the form:
Dim strDeal As String
Dim strSQL As String
strDeal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = '" & Forms!frmStructNoDASetup!Structure_Name & "' AND [FG_Ind] = 0 AND [Deal_No] < '" & Forms!frmStructNoDASetup!Deal_No & "'")
strSQL = "UPDATE tblStructuresNoDAworking " & _
"SET tblStructuresNoDAworking.Case_Qty = " & _
" (SELECT [Case_Qty] " & _
" FROM tblStructuresNoDAworking " & _
" WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & strDeal & "') " & _
"WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & Me.Deal_No.Value & "'"
DoCmd.RunSQL strSQL
For numeric Deal:
Dim Deal As Long
Dim strSQL As String
Deal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = '" & Forms!frmStructNoDASetup!Structure_Name & "' AND [FG_Ind] = 0 AND [Deal_No] < '" & Forms!frmStructNoDASetup!Deal_No & "'")
strSQL = "UPDATE tblStructuresNoDAworking " & _
"SET tblStructuresNoDAworking.Case_Qty = " & _
" (SELECT [Case_Qty] " & _
" FROM tblStructuresNoDAworking " & _
" WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = " & Deal & ") " & _
"WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = " & Me.Deal_No.Value & ""
DoCmd.RunSQL strSQL

How concatenate recordset variables to use filter method - Vba

I would like to concatenate multiple variables on my recordset filter. Here more information :
rs is recordset
titre can be M. or Mme or S. (come from rs)
Nom is of the form (come from rs) : FirstName LastName (with space between)
but I can't. I tried :
space = " "
rs.Filter = "[titre+ space + Nom] = '" & oLookFullName & "' and nomEntreprise = '" & objContact.CompanyName & "'"
Concatenation = rs!titre + " " + rs!Nom
rs.Filter = "Concatenation = '" & oLookFullName & "'"
Any ideas ?
EDIT
#Gustav, I tried your code with split and it seems the filter contains the correct value but just after I have this if loop and in this case rs.EOF is true while the contact exists... why ?
If rs.EOF Then 'Or (rs.BOF = True) Then
Debug.Print oLookFullName & " is not found."
End If
Try with:
rs.Filter = "[titre] & ' ' & [Nom] = '" & oLookFullName & "' And [nomEntreprise] = '" & objContact.CompanyName & "'"
or:
rs.Filter = "[titre] = '" & Split(oLookFullName, " ")(0) & "' And [Nom] = '" & Split(oLookFullName, " ")(1) & "' And [nomEntreprise] = '" & objContact.CompanyName & "'"

VBA error matching date from table and date from query when date has leading zero eg 01/04 or 02/04

I have a query in MS Access called qryRMCountStudentsBySessionWP. The results are shown below.
I have some VBA code shown below. Basically if the Timetable_Date, Timetable_Session and Location match Exam_Date, Exam_Session and Exam_Location of a record in a table called Invigilation, then changes are made to that record's start time.
This works fabulously for 30/03/2020 and 31/03/2020 but not any of the April dates. I think this is because of leading zeros but I just can't figure out how to fix it. Any ideas?
Private Sub wordProcessing()
Dim dbs As Database
Dim name As String
Dim SQL As String
Dim rstAllSessions As Recordset
Set dbs = CurrentDb
SQL = "SELECT Timetable_Date, Timetable_Session, Location, CountOfStudent_Ref FROM qryRMCountStudentsBySessionWP;"
Set rstAllSessions = dbs.OpenRecordset(SQL)
rstAllSessions.MoveFirst
Do Until rstAllSessions.EOF ' for each sesson update invigilation table
If rstAllSessions.Fields(3) >= 10 Then
If rstAllSessions.Fields(1) = "A" Then
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('08:30:00'), Notes = 'WP Exam with 10 or more students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
Else
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('13:00:00'), Notes = 'WP Exam with 10 or more students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
End If
ElseIf rstAllSessions.Fields(3) >= 5 Then
If rstAllSessions.Fields(1) = "A" Then
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('08:35:00'), Notes = 'WP Exam with 5 or more students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
Else
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('13:05:00'), Notes = 'WP Exam with 5 or more students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
End If
ElseIf rstAllSessions.Fields(3) > 1 Then
If rstAllSessions.Fields(1) = "A" Then
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('08:40:00'), Notes = 'WP Exam with >1 and <5 students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
Else
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('13:10:00'), Notes = 'WP Exam with >1 and <5 students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
End If
Else
If rstAllSessions.Fields(1) = "A" Then
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('08:45:00'), Notes = 'WP Exam with 1 student' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
Else
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('13:15:00'), Notes = 'WP Exam with 1 student' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
End If
End If
' doesn't do dates with leading 0s?????
rstAllSessions.MoveNext
Loop
rstAllSessions.Close
dbs.Close
End Sub
Date values are numeric, thus no leading zeroes. But you must pass properly formatted string expressions for the date values when concatenating:
"UPDATE Invigilation SET Start_Time = TimeSerial(13,15,0), Notes = 'WP Exam with 1 student' WHERE Invigilation.Exam_Date = #" & Format(rstAllSessions!Timetable_Date, "yyyy\/mm\/dd") & "# AND Invigilation.Exam_Location = '" & rstAllSessions!Location & "' AND Invigilation.Exam_Session = '" & rstAllSessions!Timetable_Session & "';"

Fast and reliable way to insert into SQL table from vb.net Datagridview which has more than thousand rows

I would really appreciate if someone can help me to find a better solution than what I am doing now.
this is my vb.net insert command from the form which has dgvs with tables of 'dtOrders' and 'dtItems'. The issue I am facing now that sometimes all selected data doesn't insert into sql over internet dueto connection drop or slow connection. So what I want is send all data at once to sql and do the insert in sql stored procedure or something like that.
Sub Inserts() ' ScanPointLog, spSendToFactory
Dim CurrentDate = DateTime.Now.ToString("dd MMMM, yyyy hh:mm tt")
Try
'Insert Into ScanPointLog
MyCon.Open()
Query = "Declare #tId int set #tId=(select count(TripId) from ScanPointLog where BranchCode='" & BranchCodee & "' and ScanPoint='" & ScanPointName & "')+1
Insert into ScanPointLog(BranchCode, ScanPoint, TripId, DoneBy, DateTime, Driver, CarNo, ItemShouldBe, ActualTaken, MissedAny, MissedCount, TookExtra, ExtraCount, chkdSkipTrackItem, chkdSelectAllOrders,[Open])
Values('" & BranchCodee & "','" & ScanPointName & "',#tId,'" & UserIdd & "','" & CurrentDate & "','" & cmbDrivers.SelectedValue & "','" & txtCarNo.Text & "','" & TotalItemShouldBeForSelectedOrders & "','" & TotalItemTackenInTheTrip & "','" & IsThereAnyMissing & "','" & missingItems & "', '" & IsThereExtras & "','" & takingExtras & "',#skipTrckItem, #chckdAllOrdrs,1 )"
Command = New SqlCommand(Query, MyCon)
Command.Parameters.Add("#skipTrckItem", SqlDbType.Bit).Value = Convert.ToInt16(chbByPassTrackItem.Checked)
Command.Parameters.Add("#chckdAllOrdrs", SqlDbType.Bit).Value = Convert.ToInt16(chbSelectAllOrders.Checked)
Command.ExecuteNonQuery()
MyCon.Close()
'to get the saving tripid which was automatically took from above inser query
MyCon.Open()
Query = "Declare #tId int set #tId=(select count(TripId) from ScanPointLog where BranchCode='" & BranchCodee & "' and ScanPoint='" & ScanPointName & "')
select #tId as Result"
Command = New SqlCommand(Query, MyCon)
dtreaderTripIdafterSave = Command.ExecuteReader
While dtreaderTripIdafterSave.Read
ThisTripID = dtreaderTripIdafterSave.Item(0)
End While
lblTripID.Text = ThisTripID
MyCon.Close()
'Insert Orders into table spSendToFactory
MyCon.Open()
For Each row As DataRow In dtOrders.Rows
If row("Checked") = True Then
Dim TrackItem As Integer
If row("TrackItem") = "Yes" Then
TrackItem = 1
Else
TrackItem = 0
End If
Query = "If not Exists (Select * from spSendToFactory where OrderNo = #nOrderNo and IsItem=0 and BranchCode=#nBranchcode )
begin
Insert into spSendToFactory(OrderNo, DateTime, IsItem, BranchCode, TrackItem,CameFrom_Page,CameFrom_Table,CameFrom_TripID) Values(#nOrderNo,#nDtTm,0,#nBranchcode,#trkItem,'" & PreviouseScanPoint_Form & "','" & PreviouseScanPoint_Table & "','" & ThisTripID & "')
end;
Update spOrdered set TripId= '" & ThisTripID & "',Done= 1 where OrderNo = #nOrderNo AND IsItem=0;
Update Orders set OrderStatus= '" & ScanPointName & "' where OrderNo = #nOrderNo "
Command = New SqlCommand(Query, MyCon)
Command.Parameters.AddWithValue("#nOrderNo", row("OrderNo").ToString)
Command.Parameters.AddWithValue("#nDtTm", CurrentDate)
Command.Parameters.AddWithValue("#nBranchcode", BranchCodee)
Command.Parameters.Add("#trkItem", SqlDbType.Bit).Value = TrackItem
Command.ExecuteNonQuery()
End If
Next
'Insert Items into table spSendToFactory
For Each iRow As DataRow In dtItems.Rows
If iRow("Checked") = True Then
Query = "If not Exists (Select * from spSendToFactory where OrderNo = #nOrderNo and IsItem=1 and ItemBarcode=#nItemBcode and BranchCode=#nBranchcode )
begin
Insert into spSendToFactory(OrderNo, DateTime, IsItem, ItemBarcode, BranchCode,CameFrom_Page,CameFrom_Table,CameFrom_TripID ) Values(#nOrderNo,#nDtTm,1,#nItemBcode,#nBranchcode,'" & PreviouseScanPoint_Form & "','" & PreviouseScanPoint_Table & "','" & ThisTripID & "')
end;
Update spOrdered set TripId= '" & ThisTripID & "', Done= 1 where OrderNo = #nOrderNo AND IsItem=1 AND ItemBarcode= #nItemBcode ;
Update OrderItem set ItemStatus= '" & ScanPointName & "' where OrderNo = #nOrderNo AND ItemBarcode= #nItemBcode "
Command = New SqlCommand(Query, MyCon)
Command.Parameters.AddWithValue("#nOrderNo", iRow("OrderNo").ToString)
Command.Parameters.AddWithValue("#nDtTm", CurrentDate)
Command.Parameters.AddWithValue("#nItemBcode", iRow("ItemBarcode").ToString)
Command.Parameters.AddWithValue("#nBranchcode", BranchCodee)
Command.ExecuteNonQuery()
End If
Next
'Insert missing items into ScnPntMissItems
For Each mRow As DataRow In dtMissedItems.Rows
Query = "If not Exists
(Select * from ScnPntMissItems where
[BranchCode]='" & BranchCodee & "' and
[ScanPoint]= '" & ScanPointName & "' and
[TripId] = '" & ThisTripID & "' and
[OrderNo]= #nOrderNo and
[ItemBarcode] = #nItemBcode)
begin
Insert into ScnPntMissItems([BranchCode],[ScanPoint],[TripId],[DateTime],[OrderNo],[ItemName],[ItemBarcode]) Values('" & BranchCodee & "','" & ScanPointName & "','" & ThisTripID & "','" & CurrentDate & "',#nOrderNo,#nItemName,#nItemBcode)
end"
Command = New SqlCommand(Query, MyCon)
Command.Parameters.AddWithValue("#nOrderNo", mRow("OrderNo").ToString)
Command.Parameters.AddWithValue("#nItemName", mRow("ItemName").ToString)
Command.Parameters.AddWithValue("#nItemBcode", mRow("ItemBarcode").ToString)
Command.ExecuteNonQuery()
Next
'Insert extra items into ScnPntExtraItems
For Each eRow As DataRow In dtExtarItems.Rows
Query = "If not Exists
(Select * from ScnPntExtraItems where
[BranchCode]='" & BranchCodee & "' and
[ScanPoint]= '" & ScanPointName & "' and
[TripId] = '" & ThisTripID & "' and
[OrderNo]= #nOrderNo and
[ItemBarcode] = #nItemBcode)
begin
Insert into ScnPntExtraItems([BranchCode],[ScanPoint],[TripId],[DateTime],[OrderNo],[ItemName],[ItemBarcode]) Values('" & BranchCodee & "','" & ScanPointName & "','" & ThisTripID & "','" & CurrentDate & "',#nOrderNo,#nItemName,#nItemBcode)
end;
Update spOrdered set TripId= '" & ThisTripID & "', Done= 1 where OrderNo = #nOrderNo AND IsItem=1 AND ItemBarcode= #nItemBcode ;
Update OrderItem set ItemStatus= '" & ScanPointName & "' where OrderNo = #nOrderNo AND ItemBarcode= #nItemBcode"
Command = New SqlCommand(Query, MyCon)
Command.Parameters.AddWithValue("#nOrderNo", eRow("OrderNo").ToString)
Command.Parameters.AddWithValue("#nItemName", eRow("ItemName").ToString)
Command.Parameters.AddWithValue("#nItemBcode", eRow("ItemBarcode").ToString)
Command.ExecuteNonQuery()
Next
Query = "Update ScanPointLog set [Close]=1 where BranchCode='" & BranchCodee & "' and ScanPoint='" & ScanPointName & "' and TripId= '" & ThisTripID & "' "
Command = New SqlCommand(Query, MyCon)
Command.ExecuteNonQuery()
MyCon.Close()
failed_to_upload = False
MsgBox("Trip ID: " & ThisTripID & " at '" & ScanPointName & "' saved successfully")
Catch ex As Exception
MsgBox(ex.Message)
failed_to_upload = True
MsgBox("The uploading process could NOT be completed properly due to network issue.
The Trip ID '" & ThisTripID & "' of '" & ScanPointName & "' may not include checked orders or items correctly. Therefor please contact system administrator with following details to roll back this event immediately.
Trip ID = '" & ThisTripID & "'
Scan Point = '" & ScanPointName & "'")
End Try
End Sub

keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error

Good day, I keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error.
Can someone please assist with why and where?
Any help will be greatly appriciated
Below is the code
Try
conec.Open()
Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName = '" & TxtName.Text & "', LastName = '" & txtSurname.Text & "', Access = '" & cmbAccess.SelectedItem & "', CreatedBY = '" & Label9.Text & "', DateCreated = '" & Label10.Text & "', ChangedBY = '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd hh:mm tt") & "' WHERE UserName = " & txtUserName.Text & ";")
cmd.CommandType = CommandType.Text
cmd.Connection = conec
cmd.ExecuteNonQuery()
MessageBox.Show("Data Updated" & vbCrLf & "Done")
conec.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Looks like you're missing apostrophes in your where clause, try:
Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName = '" & TxtName.Text & "', LastName = '" & txtSurname.Text & "', Access = '" & cmbAccess.SelectedItem & "', CreatedBY = '" & Label9.Text & "', DateCreated = '" & Label10.Text & "', ChangedBY = '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd hh:mm tt") & "' WHERE UserName = '" & txtUserName.Text & "';")
I recommend using SQL Parameters however, they're a lot easier to maintain.