I have an Excel table with 5 columns and 3 rows with data. Every time the data changes it is uploaded to DB. Below is my code to send data from the Excel table to the existing table in SQL Server. The challenge is, that the database accepts unique ID values. I would be grateful for your help on how to change the code that when ID in an Excel table already exists in the database? The code terminates with the message:
Duplicates are not allowed!
Sub IMPORT()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Dim r As Range
con.ConnectionString = sqlconstr
con.Open "Provider=sqloledb;Data Source=DS;Initial Catalog=AUTO;Integrated Security=SSPI"
cmd.ActiveConnection = con
For Each r In Range("a2", Range("a2").End(xlDown))
If r.Offset(0, 4).Value <> "" Then
cmd.CommandText = cmd.CommandText & _
GetInsertText( _
r.Offset(0, 0).Value, _
r.Offset(0, 1).Value, _
r.Offset(0, 2).Value, _
r.Offset(0, 3).Value, _
r.Offset(0, 4).Value _
)
End If
Next r
Debug.Print cmd.CommandText
cmd.Execute
con.Close
Set con = Nothing
msgbox "Import successful"
End Sub
Function GetInsertText(ID As String, Date1 As Date, Date2 As Date, Reference As String, Price As Double)
sql = _
"insert into dbo.TP (" & _
"ID, Date1, Date2, Reference, Price)" & _
"values (" & _
"'" & ID & "'," & _
"'" & Format(Date1, "yyyy-mm-dd") & "'," & _
"'" & Format(Date2, "yyyy-mm-dd") & "'," & _
"'" & Reference & "'," & _
Replace(Format(Price, "#0.00"), ",", ".") & ");"
GetInsertText = sql
End Function