Wednesday, November 16, 2011

Quickly disable triggers and keys


/* run before importing data */
-- SQL disable all triggers - disable all triggers sql server - t sql disable trigger
EXEC sp_MSforeachtable @command1="ALTER TABLE ? DISABLE TRIGGER ALL"
GO
-- SQL disable all constraints - disable all constraints sql server
EXEC sp_MSforeachtable @command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
GO
/* deletes all existing data */
-- SQL disable all constraints - disable all constraints sql server
EXEC sp_MSforeachtable @command1="DELETE FROM ? "
GO

/* run after importing data */
-- SQL enable all triggers - enable all triggers sql server - t sql enable trigger
EXEC sp_MSforeachtable @command1="ALTER TABLE ? ENABLE TRIGGER ALL"
GO
-- SQL enable all constraints - enable all constraints sql server
-- sp_MSforeachtable is an undocumented system stored procedure
EXEC sp_MSforeachtable @command1="ALTER TABLE ? CHECK CONSTRAINT ALL"
GO