当前位置:  开发笔记 > 编程语言 > 正文

如何一次删除所有ms访问表中的数据?

如何解决《如何一次删除所有ms访问表中的数据?》经验,为你挑选了3个好方法。

MS-Access中是否有一种方法可以一次删除所有表中的数据.我们在访问中运行数据库,每月保存数据,然后删除访问中的所有数据.但它需要从许多表中删除数据.是不是有更简单/更简单的方法呢?



1> Craig T..:

为什么不保留数据库的空副本.在月末,保存现有数据库,然后将空数据库复制到其位置.



2> Alistair Kno..:

克雷格的回答简单而明智.如果您确实需要编程解决方案,则以下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



3> Marcin D..:

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

推荐阅读
大大炮
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有