Monday, May 6, 2019

how to disable and enable the triggers in SQL to increase the SQL execution time

//Disable
Declare @SQLTrigger varchar(max)
 set @SQLTrigger=  'dbo.sp_MSforeachtable @command1='+'"'+'DISABLE TRIGGER ALL ON ?'+'" '
 exec(@SQLTrigger)


//Enable
 Declare @SQLTrigger varchar(max)
 set @SQLTrigger=  'dbo.sp_MSforeachtable @command1='+'"'+'Enable TRIGGER ALL ON ?'+'" '
 exec(@SQLTrigger)

To disable and enable all constraints on a database

//DIsable

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"


//ENable
EXEC sp_msforeachtable "ALTER TABLE ? CHECK CONSTRAINT all"

To know reference tables(foreign key) for a table, SQLSERVer

SELECT CONSTRAINT_NAME = name,
       FOREIGN_SCHEMA = OBJECT_SCHEMA_NAME(parent_object_id),
       FOREIGN_TABLE = OBJECT_NAME(parent_object_id),
       REFERENCED_SCHEMA = OBJECT_SCHEMA_NAME(referenced_object_id),
       REFERENCED_TABLE = OBJECT_NAME(referenced_object_id)
FROM sys.foreign_keys
WHERE OBJECT_NAME(referenced_object_id) = 'TableName';
GO