2010-10-20 59 views
0

如何在SQL中進行查詢以刪除每個表中存在的所有記錄。刪除所有表中存在的所有記錄

有可能使用命令delete寫每個名稱表。但編寫每一個名字表需要很長時間。

我已經嘗試在MySQL DELETE FROM *但它得到了錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*' at line 1

+0

那麼,這是在PHP?我在C#中提供了一個答案(有點僞)... – IAbstract 2010-10-20 04:57:37

+1

Duplicate http://stackoverflow.com/questions/935284/is-there-a-way-to-truncate-most-tables-in-a-mysql-模式 http://stackoverflow.com/questions/454174/how-to-empty-all-rows-from-all-tables-in-mysql-in-sql – 2010-10-20 05:12:21

+0

@dboarman:不,實際上我想插入記錄後我刪除所有記錄存在數據庫。謝謝 – 2010-10-20 08:00:29

回答

1

你只需要做爲每個表TRUNCATE查詢。你也可以使用刪除,但截斷通常更適合你正在做的事情。

TRUNCATE TABLE table1; 
TRUNCATE TABLE table2; 
TRUNCATE TABLE table2; 

沒有*或全部表選擇器。

0

我相信MySQL有一個SQL語句如下:

Show tables 

作爲命令文本與Show tables創建命令對象,並執行。

使用該語句,您可以執行查詢並填充MySqlDataReader。按照以下方式迭代閱讀器並將表格名稱放入格式化的字符串中。

// create connection string 
... 
while (myDataReader.Read()) 
{ 
    // execute command 
    string command = "TRUNCATE TABLE {0}"; 

    MySqlCommand myCommand = new MySqlCommand(); 
    myCommand.CommandText = string.Format(command, reader[0]); 

    using (MySqlConnection myConnection = new MySqlConnection(myConnString)) 
    { 
     myCommand.Connection = myConnection; 
     myCommand.Connection.Open(); 

     myCommand.ExecuteNonQuery(); 
    } 
} 

這應該足夠接近以幫助您走上正確的軌道。

0

您可以使用INFORMATION_SCHEMA遍歷所有表並動態執行DELETE或TRUNCATE語句。

0

DELETE語句可以使用。

以下將刪除所有行,但索引(例如自動增量)將不會被重置。

DELETE * FROM TABLEX

下面將刪除所有行也索引將被重置

TRUNCATE TABLEX

1

請使用

<?php 
mysql_connect('localhost', 'user', 'password'); 
$dbName = "database"; 
mysql_select_db($dbName) 
$result_t = mysql_query("SHOW TABLES"); 
while($row = mysql_fetch_assoc($result_t)) 
{ 
    mysql_query("TRUNCATE " . $row['Tables_in_' . $dbName]); 
} 
?> 

所有最優秀的

0

如果你想自動完成這個,你必須編寫一些MySQL外部的代碼。使用show tables來獲取表名,然後在每個表上調用TRUNCATE