【发布时间】:2021-08-18 22:19:45
【问题描述】:
我有一个包含 5 列和 3 行数据的 Excel 表。每次数据更改时,它都会上传到数据库。下面是我将数据从 Excel 表发送到 SQL Server 中现有表的代码。挑战在于,数据库接受唯一的 ID 值。如果您在 Excel 表中的 ID 已存在于数据库中时如何更改代码,我将不胜感激?代码以消息结束:
不允许重复!
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
【问题讨论】:
-
@StureS 你能解释一下你为什么在这里发布谷歌搜索结果吗?
-
一种方法是使用 SELECT 语句。如果记录存在,则执行 UPDATE,否则执行 INSERT。
-
@Dejan Dozet:谷歌搜索包含许多解决您问题的建议
-
当然可以,但这也意味着我们可以在发帖之前回复任何人检查谷歌搜索,这不是一个好主意。让他们在这里问他们想问的任何问题,并尝试直接回答他们的问题。
标签: sql excel vba sql-insert