Saturday, 21 April 2012

How to Delete all records from all tables from Database

It is very serious one. Please do carefully


Following is the SQL query used to delete all records from all tables from Database.
This is useful during development scenarios where you need to get rid of all the dummy records and insert a fresh data.

SQL Query: Appropriate comments are provided to explain its operation





/* The Following set of queries is used to delete all records from all tables from your database */
/* Disables Referential integrity */
/*---------------------------------*/
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
/* Delete records from tables */
/*----------------------------*/
EXEC sp_MSForEachTable '
IF OBJECTPROPERTY(object_id(''?''), ''TableHasForeignRef'') = 1
DELETE FROM ?
else
TRUNCATE TABLE ?
'
GO
/* Enables Referential integrity */
/*-------------------------------*/
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO
/*Query ot be used if you would like to reseed all table*/
/*------------------------------------------------------*/
EXEC sp_MSForEachTable '
IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1
DBCC CHECKIDENT (''?'', RESEED, 0)
'
GO


Source : http://mrsupport.blogspot.in/

No comments:

Post a Comment