Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

I use SQL server 2008 R2.

Is there a SQL command to empty the database, instead of having to truncate all 20 my tables?

I just want to delete the data not the structure.

like image 640
user609511 Avatar asked May 17 '11 09:05

user609511


People also ask

Can you truncate multiple tables in SQL?

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.

How do you truncate all tables in SQL Server with foreign key constraint?

You cannot truncate a table that has foreign key constraints. I would script your truncate statement to drop the constraints, then truncate the table, and then re-create the constraints.

How do I truncate a database?

Select Database -> More Database Operations -> Truncate Database (Shift+Del) to truncate (make the tables empty) all the tables of a database (however, the Tables and other objects (Stored Procedures, Views etc.) are not dropped).


2 Answers

You can use the sp_MSforeachtable stored procedure like so:

USE MyDatabase EXEC sp_MSforeachtable 'TRUNCATE TABLE ?' 

Be warned that this will delete (by truncation) ALL data from all user tables. And in case you can't TRUNCATE due to foreign keys etc. you can run the same as a delete:

USE MyDatabase EXEC sp_MSforeachtable 'DELETE FROM ?' 
like image 131
Mark S. Rasmussen Avatar answered Oct 11 '22 10:10

Mark S. Rasmussen


I use this script

EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’ EXEC sp_MSForEachTable ‘DELETE FROM ?’ EXEC sp_MSForEachTable ‘ALTER TABLE ? CHECK CONSTRAINT ALL’ GO 
like image 29
Boycs Avatar answered Oct 11 '22 10:10

Boycs