CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: SQL

Truncate all table in a database in sql server

243 Views
Copy Code Show/Hide Line Numbers
Set NoCount ON
 
Declare @tableName varchar(200)
 
set @tableName=''
 
While exists
 
(
 
--First of all getting all child table that has no any relations
 
select T.table_name from INFORMATION_SCHEMA.TABLES T
 
left outer join INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
 
on T.table_name=TC.table_name where (TC.constraint_Type ='Foreign Key'
 
or TC.constraint_Type is NULL) and
 
T.table_name not in ('dtproperties','sysconstraints','syssegments')
 
and Table_type='BASE TABLE' and T.table_name > @TableName
 
)
 
Begin
 
Select @tableName=min(T.table_name) from INFORMATION_SCHEMA.TABLES T
 
left outer join INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
 
on T.table_name=TC.table_name where (TC.constraint_Type ='Foreign Key'
 
or TC.constraint_Type is NULL) and
 
T.table_name not in ('dtproperties','sysconstraints','syssegments')
 
and Table_type='BASE TABLE' and T.table_name > @TableName
 
--Truncate table here
 
Exec('Truncate table '+@tableName)
 
End
 
set @TableName=''
 
While exists
 
(
 
--here fetch all Parent tables
 
select T.table_name from INFORMATION_SCHEMA.TABLES T
 
left outer join INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
 
on T.table_name=TC.table_name where TC.constraint_Type ='Primary Key'
 
and T.table_name <>'dtproperties'and Table_type='BASE TABLE'
 
and T.table_name > @TableName
 
)
 
Begin
 
Select @tableName=min(T.table_name) from INFORMATION_SCHEMA.TABLES T
 
left outer join INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
 
on T.table_name=TC.table_name where TC.constraint_Type ='Primary Key'
 
and T.table_name <>'dtproperties'and Table_type='BASE TABLE'
 
and T.table_name > @TableName
 
--Delete all table here
 
Exec('Delete from '+@tableName)
 
--------now reset identity
 
If exists(
 
SELECT * FROM information_schema.columns
 
WHERE COLUMNPROPERTY(OBJECT_ID(
 
QUOTENAME(table_schema)+'.'+QUOTENAME(@tableName)),
 
column_name,'IsIdentity')=1
 
)
 
DBCC CHECKIDENT (@tableName, RESEED, 1)
 
End
 
-- disable referential integrity
 
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
 
GO
 
EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'
 
GO
 
-- enable referential integrity again
 
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
 
GO
 
Set NoCount Off
by Unknown (google)
  April 16, 2010 @ 12:00pm
Tags:
Description:
To perform an action on all of the tables within a database

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate