我在excel中有一个子程序,我想将数据写入Access表。我正在尝试更新表中的一行(如果它已经存在),如果不存在则添加它。离开Jeremiah Clark在这个MSDN博客上给出的suggestion,我得知我将从Excel的VBA子程序执行:
UPDATE tblName
SET [Column1] = 'text', ...(other values)... [ColumnN] = 1234
WHERE ([Column1] = 'text' AND [Column2] = 'text2')
If @@ROWCOUNT = 0
INSERT INTO tblName
VALUES ( [Column1] = 'text', ...(other values)... [ColumnN] = 1234 )
它给我的错误是:
Syntax error (missing operator) in query expression '([Column1] = 'text' AND [Column2] = 'text2')
If @@ROWCOUNT = 0
INSERT INTO tblName
VALUES ( [Column1] = 'text', ...(other values)...'.
我对SQL很陌生,但是如果评估顺序不符合我的预期,我已经尝试了各种方法将IF线包围(括号),但这无济于事。查询的第一部分是否未被评估,因此@@ ROWCOUNT无法正确执行?
Edit1 :如果重要,请使用Access 2003。
解决方案: 基于bluefeet's suggestion(参见他的整个回复):
objDB.Execute sqlStrSelect
recordset.Source = sqlStrSelect
recordset.Open , , adOpenDynamic, adLockOptimistic
If recordset.Fields(0) = 0 Then
objDB.Execute sqlStrInsert
Else
objDB.Execute sqlStrUpdate
End If
这依赖于修改后的SELECT查询来获取Access以返回记录的计数:
sqlStrSelect = "SELECT Count(id) FROM table1 WHERE id = 3"
HansUp正确地推测我使用的是ADO连接,因此执行代码必须与bluefeet最初建议的不同。
答案 0 :(得分:3)
@@ROWCOUNT
用于SQL Server而非Access,但由于您使用的是VBA
,因此您可以执行与此类似的操作。基本上将您的SQL语句创建为输入您要检查的值的字符串。然后首先针对表运行查询以查看记录是否存在,如果存在则执行UPDATE
如果不存在则执行INSERT
。我在MS Access 2003中快速测试了它并且它可以工作。
Public Sub test()
Dim sqlStrUpdate As String
Dim sqlStrSelect As String
Dim sqlStrInsert As String
Dim recordSet As recordSet
sqlStrUpdate = "UPDATE table1 SET Field1 = " & 5 & " WHERE id = 3"
sqlStrSelect = "SELECT id FROM table1 WHERE id = 3"
sqlStrInsert = "INSERT INTO table1 (id, Field1, Field2, Field3) VALUES (3, 5, 0, 0)"
Set recordSet = CurrentDb.OpenRecordset(sqlStrSelect)
If recordSet.RecordCount > 0 Then
DoCmd.RunSQL (sqlStrUpdate)
ElseIf recordSet.RecordCount = 0 Then
DoCmd.RunSQL (sqlStrInsert)
End If
End Sub
编辑:正如HansUp指出您正在使用Excel查询,您的代码可能与此类似:
Public Sub test_new()
Dim cDir_Database As String
Dim DB_Conn As New ADODB.Connection 'Access Connection
Dim DB_RSet As New ADODB.recordSet 'Access Record Set
Dim sqlStrUpdate As String
Dim sqlStrInsert As String
cDir_Database = ".\.\.AccessBD.mdb "
sqlStrUpdate = "UPDATE table1 SET Field1 = " & 10 & " WHERE id = 4"
sqlStrInsert = "INSERT INTO table1 (id, Field1, Field2, Field3) VALUES (4, 5, 0, 0)"
DB_Conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};" & _
"DBQ=" & cDir_Database & ";"
DB_Conn.Open
DB_Conn.BeginTrans
DB_RSet.Open "SELECT id FROM table1 WHERE id = 4", DB_Conn, adOpenStatic, adLockReadOnly
If DB_RSet.RecordCount > 0 Then
DB_Conn.Execute (sqlStrUpdate)
ElseIf DB_RSet.RecordCount = 0 Then
DB_Conn.Execute (sqlStrInsert)
End If
DB_RSet.Close
DB_Conn.CommitTrans
DB_Conn.Close
End Sub
这已经从Excel 2003测试到Access 2003并且有效。您需要将引用添加到Microsoft ActiveX数据对象的Excel文件中。