如何用SQL删除所有表上的所有记录(1次)

时间:2012-11-04 10:21:29

标签: sql ms-access sql-delete

我在1个ms-access文件中有14个表。

我想一次删除这些表上的所有记录。

我尝试

DELETE FROM table1
DELETE FROM table2
DELETE FROM table3
...
DELETE FROM table12
DELETE FROM table13
DELETE FROM table14

并运行它。

但它无法运行。

怎么做?

1 个答案:

答案 0 :(得分:2)

您只能在MS Access SQL中一次运行一条语句,但是,您可以使用MS Access VBA:

Sub DeleteTables()
    CurrentDB.Execute "DELETE FROM Table1", dbFailOnerror
    CurrentDB.Execute "DELETE FROM Table12", dbFailOnerror
End Sub

或更好

astables = Split("table1,table2,table3", ",")

For Each tbl In astables
    CurrentDb.Execute "DELETE FROM " & tbl, dbFailOnError
Next

如果任何表与其他表有关系,您必须确保以特定顺序删除。

如果要从所有表中删除并且顺序无关紧要,可以使用TableDefs集合,注意不要从系统表中删除。这是一个非常危险的选择:

For Each tdf In CurrentDb.TableDefs
    If Left(tdf.Name, 4) <> "Msys" And Left(tdf.Name, 1) <> "~" Then
        CurrentDb.Execute "DELETE FROM " & tdf.Name, dbFailOnError
    End If
Next