Thursday, December 3, 2015

Script to enable and disable all the triggers in SQL Server

========Script to generate trigger enable==============
SELECT 'ALTER TABLE ['+ SC.NAME+'].[' + PB.NAME + '] ENABLE TRIGGER ALL'
FROM SYS.TRIGGERS T
JOIN SYS.ALL_OBJECTS OB ON OB.OBJECT_ID = T.OBJECT_ID
JOIN SYS.ALL_OBJECTS PB ON PB.OBJECT_ID = OB.PARENT_OBJECT_ID
JOIN SYS.SCHEMAS SC ON SC.SCHEMA_ID = PB.SCHEMA_ID


========Directly enable all trigger==================
DECLARE @string VARCHAR(8000)
DECLARE @tableName NVARCHAR(500)
DECLARE cur CURSOR
 FOR SELECT name AS tbname FROM sysobjects WHERE id IN(SELECT parent_obj FROM sysobjects WHERE xtype='tr')
OPEN cur
FETCH next FROM cur INTO @tableName
WHILE @@fetch_status = 0
BEGIN
 SET @string ='Alter table '+ @tableName + ' Enable trigger all'
--EXEC (@string)
FETCH next FROM cur INTO @tableName
END
 CLOSE cur
DEALLOCATE cur


========Script to Disable all triggers ==================
DECLARE @string VARCHAR(8000)
DECLARE @tableName NVARCHAR(500)
DECLARE cur CURSOR
 FOR SELECT name AS tbname FROM sysobjects WHERE id IN(SELECT parent_obj FROM sysobjects WHERE xtype='tr')
OPEN cur
FETCH next FROM cur INTO @tableName
WHILE @@fetch_status = 0
BEGIN
 SET @string ='Alter table '+ @tableName + ' Disable trigger all'
--EXEC (@string)
FETCH next FROM cur INTO @tableName
END
 CLOSE cur
DEALLOCATE cur

No comments:

Post a Comment