Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate all tables in MySQL database that match a name pattern

Tags:

sql

mysql

I need to clear all my inventory tables.

I've tried this:

SELECT 'TRUNCATE TABLE ' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'inventory%' 

But I get this error:

Truncated incorrect DOUBLE value: 'TRUNCATE TABLE ' Error Code 1292 

if this is the correct way, then what am I doing wrong?

like image 955
Luiscencio Avatar asked Oct 15 '09 22:10

Luiscencio


People also ask

How do I truncate a schema in MySQL?

To truncate a table, one must drop the foreign key constraints mapped to the columns in this table from other tables (in fact on all tables in the specific DB/Schema). So, all foreign key constraints must be dropped initially followed by table truncation.

Can we truncate multiple tables in MySQL?

No, you can only truncate a single table with TRUNCATE command.

How do I truncate all table records?

The SQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data.


1 Answers

Use concat:

SELECT concat('TRUNCATE TABLE `', TABLE_NAME, '`;') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'inventory%' 

This will of course only generate SQL which you need to copy and run yourself.

like image 172
ʞɔıu Avatar answered Sep 22 '22 22:09

ʞɔıu