Tuesday, December 14, 2010

Clear All Tables Records In Sql Server

The Following Query Will clear the all tables in Current Database.
Some Time We need to create fresh Database so at the time this script will more Use Full

sample Script

-------------------------------------------------------------------------------------
--Finding List Of Tables in Current DB
select Count(*) from Sys.tables
-------------------------------------------------------------------------------------




=======================================================================--------------
--Query For Clear All tables records in single instance
=====================================================================----------------

DECLARE @ResetIdentity BIT
DECLARE @SQL VARCHAR(500)
DECLARE @TableName VARCHAR(255)
DECLARE @ConstraintName VARCHAR(500)
DECLARE curAllForeignKeys SCROLL CURSOR FOR SELECT Table_Name,Constraint_Name FROM Information_Schema.Table_Constraints Where Constraint_Type='FOREIGN KEY'

SET @ResetIdentity=1

Open curAllForeignKeys
Fetch Next From curAllForeignKeys INTO @TableName,@ConstraintName
While @@FETCH_STATUS=0

BEGIN

SET @SQL = 'ALTER TABLE ' + @TableName + ' NOCHECK CONSTRAINT ' + @ConstraintName

EXECUTE(@SQL)

FETCH NEXT FROM curAllForeignKeys INTO @TableName,@ConstraintName

End





DECLARE curAllTables CURSOR FOR SELECT Table_Name FROM Information_Schema.Tables WHERE TABLE_TYPE='BASE TABLE'

Open curAllTables



Fetch Next From curAllTables INTO @TableName

While @@FETCH_STATUS=0

Begin

Set @SQL = 'DELETE FROM ' + @TableName

If @ResetIdentity = 1 AND OBJECTPROPERTY (OBJECT_ID(@TableName),'TableHasIdentity')=1

Set @SQL = @SQL + '; DBCC CHECKIDENT(''' + @TableName + ''',RESEED,0)'



Execute(@SQL)

Fetch Next From curAllTables INTO @TableName

End





Fetch First From curAllForeignKeys INTO @TableName,@ConstraintName

While @@FETCH_STATUS=0

Begin

Set @SQL = 'ALTER TABLE ' + @TableName + ' CHECK CONSTRAINT ' + @ConstraintName

Execute(@SQL)

Fetch Next From curAllForeignKeys INTO @TableName,@ConstraintName

End



CLOSE curAllTables
DEALLOCATE curAllTables
Close curAllForeignKeys
Deallocate curAllForeignKeys

-------------------------------------------------------------------------------------

--Finding List Of Tables in Current DB
select Count(*) from Sys.tables
-------------------------------------------------------------------------------------

No comments: