Tuesday 3 December 2019

MSSQL server delete all data in database, reset counter for all tables in database, and drop constraint and remove all tables and add constraint back

// Reset counter for all tables in db
exec sp_MSforeachtable @command1 = 'DBCC CHECKIDENT(''?'', RESEED, 1)'
https://stackoverflow.com/questions/2364742/sql-server-reset-identity-increment-for-all-tables




// Delete all data in db
-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 

EXEC sp_MSForEachTable 'DELETE FROM ?' 
GO 

-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL' 
GO
https://stackoverflow.com/questions/3687575/delete-all-data-in-sql-server-database

Drop all tables
-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 

-- drop all tables 
DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql
GO


-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL' 
GO
https://stackoverflow.com/questions/27606518/how-to-drop-all-tables-from-a-database-with-one-sql-query

No comments:

Post a Comment