1. 程式人生 > >SQLite清空表資料並將自增ID設為0

SQLite清空表資料並將自增ID設為0

SQL標準中有TRUNCATE TABLE語句,用來清空表的所有內容。但SQLite不支援這個語句。在SQLite中直接使用“DELETE FROM TableName”就可以了。對於大多數DBMS來說,用DELETE不如用TRUNCATE 速度快,因為TRUNCATE 不用訪問整個表,不用記錄資料的變動。

SQLite雖然不支援TRUNCATE,但它對DELETE做了優化:

“When the WHERE is omitted(略去) from a DELETE statement and the table being deleted has no triggers(觸發器), SQLite uses an optimization(優化) to erase the entire table content without having to visit each row of the table individually. This “truncate” optimization makes the delete run much faster.”

通常在清空表的時候,還需要把自增列歸零。在SQLite中定義自增列的方法如下:

CREATE TABLE TableName ( id INTEGER PRIMARY KEY AUTOINCREMENT, … );

當SQLite資料庫中包含自增列時,會自動建立一個名為 sqlite_sequence 的表。這個表包含兩個列:name和seq。name記錄自增列所在的表,seq記錄當前序號(下一條記錄的編號就是當前序號加1)。如果想把某個自增列的序號歸零,只需要修改 sqlite_sequence表就可以了。

UPDATE sqlite_sequence SET seq = 0 WHERE
name = ‘TableName’;

也可以直接把該記錄刪掉:

DELETE FROM sqlite_sequence WHERE name = ‘TableName’;

要想將所有表的自增列都歸零,直接清空sqlite_sequence表就可以了:

DELETE FROM sqlite_sequence;