I have a sheet called "DATA" in excel that I want to export to a SQL Server DB. First to check if the records exists, if it does, update it, otherwise add a new record if it doesn't.
What I have is below, but it seems extremely slow and inefficient. Is there a way to send this data in batches of say 10 rows at a time or something?
What I have is below, but it seems extremely slow and inefficient. Is there a way to send this data in batches of say 10 rows at a time or something?
Rich (BB code):
Call InitializeConnection ' calls a function that connects to the SQL Server
'everything has been previously Dim'd.
Set r = ActiveWorkbook.Sheets("DATA").Range("A1").CurrentRegion
With r
lngRows = r.Rows.Count
For i = 1 To lngRows
'Set the material numbers as the PrimaryKey
PrimaryKey = "" & ActiveWorkbook.Sheets("DATA").Range("A" & i).Value & ""
Set rsRecordSet = GetRecordsfromDB("SELECT count(*) AS record_count FROM tbl_TIC_material_master WHERE material = " & PrimaryKey)
If rsRecordSet("record_count") = 0 Then
strSQL = "INSERT INTO tbl_TABLENAME (Field 1, Field 2, Field 3, Field 4, Field 5, Field 6, Field 7, Maint_User, Maint_Date)" _
& "VALUES ('" & PrimaryKey & "', '" & r.Offset(i, 2).Value & "', '" & r.Offset(i, 3).Value & "', '" & r.Offset(i, 4).Value & "', '" & r.Offset(i, 5).Value & "', '" & r.Offset(i, 6).Value & "', '" & r.Offset(i, 7).Value & "', '" & Environ("USERNAME") & "', CAST('" & Now() & "' AS datetime))"
lngRecordsAffected = ExecuteSQL(strSQL)
Else
strSQL = "UPDATE tbl_TBLNAME SET Field 2 = 'r.offset(i,2).value', Field 3= 'r.offset(i,3).value', Field 4 = 'r.offset(i,4).value', Field 5= 'r.offset(i,5).value', Field 5 = 'r.Offset(i,5).Value', Field 6 = 'r.Offset(i,6).Value', Field 7 = 'r.Offset(i,7).Value'," _
& "Maint_User = '" & Environ("USERNAME") & "', Maint_Date = CAST('" & Now() & "'AS datetime) WHERE Field 1 = " & PrimaryKey & ""
lngRecordsAffected = ExecuteSQL(strSQL)
End If
If lngRecordsAffected <> 1 Then
strErrorMessage = "Error during Database update"
strRoutine = "Export Data"
lngErrorNumber = Err.Number
strErrorDescription = Err.Description
GoTo ErrorHandler
End If
Next i
'Clear range variables
Set rsRecordSet = Nothing
Set r = Nothing
End With
Call EndDBConnection 'Closes DB connection
End
ErrorHandler:
'Send arguments to a function that displays error information, etc.
Call DisplayError(strErrorMessage, strRoutine, lngErrorNumber, strErrorDescription)
Call EndDBConnection 'Closes DB connection