MS-Access中是否有一种方法可以一次删除所有表中的数据.我们在访问中运行数据库,每月保存数据,然后删除访问中的所有数据.但它需要从许多表中删除数据.是不是有更简单/更简单的方法呢?
为什么不保留数据库的空副本.在月末,保存现有数据库,然后将空数据库复制到其位置.
克雷格的回答简单而明智.如果您确实需要编程解决方案,则以下VBA脚本将清除除隐藏表之外的每个表中的所有数据.它需要启用DAO - 在Visual Basic编辑器中,转到工具 - >引用,并勾选Microsoft DAO 3.6对象库,然后确定:
Public Sub TruncateTables()
'Majority of code taken from a data dictionary script I can no longer source nor find the author
On Error GoTo Error_TruncateTables
Dim DB As DAO.Database
Dim TDF As DAO.TableDef
Dim strSQL_DELETE As String
Set DB = CurrentDb()
For Each TDF In DB.TableDefs
If Left(TDF.Name, 4) <> "MSys" Then
strSQL_DELETE = "DELETE FROM " & TDF.Name & ";"
DB.Execute strSQL_DELETE
End If
Next
MsgBox "Tables have been truncated", vbInformation, "TABLES TRUNCATED"
DB.Close
Exit_Error_TruncateTables:
Set TDF = Nothing
Set DB = Nothing
Exit Sub
Error_TruncateTables:
Select Case Err.Number
Case 3376
Resume Next 'Ignore error if table not found
Case 3270 'Property Not Found
Resume Next
Case Else
MsgBox Err.Number & ": " & Err.Description
Resume Exit_Error_TruncateTables
End Select
End Sub
Alistair的答案很好,虽然需要更新.旧的if语句会导致错误,旧的动态字符串不能用于名称有空格的表.它会把像"人物信息"这样的名称视为"人".我已经更新了代码,并且如果您希望某些表保留其数据,则可以更轻松地向if语句添加异常.
Public Sub TruncateTables()
'Majority of code taken from a data dictionary script I can no longer source nor find the author
On Error GoTo Error_TruncateTables
Dim DB As DAO.Database
Dim TDF As DAO.TableDef
Dim strSQL_DELETE As String
Set DB = CurrentDb()
For Each TDF In DB.TableDefs
If Not (TDF.Name Like "MSys*" Or TDF.Name Like "~*" Or Len(TDF.Connect) > 0) Then
'This will prevent system, temporary and linked tables from being cleared
strSQL_DELETE = "DELETE FROM " & "[" & TDF.Name & "]"
DB.Execute strSQL_DELETE
End If
Next
MsgBox "Tables have been truncated", vbInformation, "TABLES TRUNCATED"
DB.Close
Exit_Error_TruncateTables:
Set TDF = Nothing
Set DB = Nothing
Exit Sub
Error_TruncateTables:
Select Case Err.Number
Case 3376
Resume Next 'Ignore error if table not found
Case 3270 'Property Not Found
Resume Next
Case Else
MsgBox Err.Number & ": " & Err.Description
Resume Exit_Error_TruncateTables
End Select
End Sub