我已将VBA中的一些代码放在一起,将excel表中的数据导出到数据库,此代码(如下)当前只是插入数据,但我想根据键(日期)插入它。因此,如果日期已经存在,那么在DB中,与该日期相关联的记录将被替换,如果该日期尚不存在,则照常插入。
当前代码:
Sub SendData(AB As String, CD As String, EF As String, GH As String, IJ As String, KL As Double, MN As Double, PQ As Double, RS As Double)
Dim Date As String, Entity As String, area As String, unit As String, name As String, surname As String
Dim day As Double, weekly As Double, month As Double, year As Double
Dim objConn As ADODB.Connection
Set objConn = New ADODB.Connection
objConn.ConnectionString = "Provider=SQLOLEDB;Data Source=source;Initial Catalog=Title;Integrated Security=SSPI"
objConn.Open
Set objRec = New ADODB.Recordset
Date = Format(Range("date").Value, "YYYY-MM-DD")
Entity = AB
area = CD
unit = EF
name = GH
surname = IJ
daily = KL
weekly = MN
month = PQ
year = RS
StrSQL = "insert into table_name values ('" & Date & "', '" & Entity & _
"','" & area & "','" & unit & "','" & name & "','" & surname & "'," & daily & "," & weekly & "," & month & "," & year & ")"
Set objRec = objConn.Execute(StrSQL)
objConn.Close
Set objConn = Nothing
end sub
我有点困惑在哪里放置钥匙...... 感谢
答案 0 :(得分:2)
您可以执行类似
的操作StrSQL = "SELECT * FROM table_name"
objRec.Open StrSQL, objConn, , adLockOptimistic
objRec.Find "[date_value] = #" & Date & "#",,,adBookmarkFirst
If objRec.EOF Then
objRec.AddNew "[date_value] = #" & Date & "#"
End If
objRec![Entity] = Entity
'repeat for all required fields
objRec.Update
objRec.Close
我不是100%确定没有小错误,因为我从我自己的工作代码中“翻译”了它,但是一般的想法和说明应该是正确的。这样您就可以利用记录集机制。我不确定性能,也许更先进的人会批评它的速度慢,但它对我有用。
答案 1 :(得分:1)
首先,我会将“日期”更改为“TheDate”或其他一些描述性但非保留的单词。此外,插入是插入,更新是更新。更新(不是插入)应该是这样的:
StrSQL = "UPDATE table_name SET values ('" & Date & "', '" & Entity & _
"','" & area & "','" & unit & "','" & name & "','" & surname & "'," & daily & "," & weekly & "," & month & "," & year & ")
WHERE " & sWhere
或者,请考虑使用MERGE clause
。
答案 2 :(得分:0)
查看sql joins
您可以为更新添加联接,然后另一个用于插入,如果您正在执行整个范围,如果不使用select count(ID) from [table_name] where [date_value]='your date'
之类的内容并使用{{1} }语句基于结果记录集记录计数或在单独的rst中在proc开始时执行目标表的if
并使用select [date_value] from [table_name]
查看它是否存在