如何获取数据库上的活动触发器列表?

时间:2012-03-09 12:46:23

标签: sql-server triggers sql-server-2008-r2

我的应用程序基于sql server db。

除自定义外,所有客户都拥有相同的数据库。

一些自定义包括:新表,修改表,自定义视图,自定义触发器......

当我运行软件更新时,会执行一些脚本。现在我手动禁用触发器并在脚本完成后重新启用。

无论如何,我想自动禁用所有触发器(已启用,可能已经禁用其中一些),然后在最后重新启用它们。

不要重新发明,怎么做?

如何只获取当前数据库上的活动触发器?

一旦我得到了这个,我就可以通过编程方式创建并运行

DISABLE TRIGGER triggername ON TABLENAME

ENABLE TRIGGER triggername ON TABLENAME

9 个答案:

答案 0 :(得分:21)

select objectproperty(object_id('TriggerName'), 'ExecIsTriggerDisabled') 

1表示true,0表示错误

使用Jeff O的查询并稍微修改

SELECT  
       TAB.name as Table_Name 
     , TRIG.name as Trigger_Name
     , TRIG.is_disabled  --or objectproperty(object_id('TriggerName'), 'ExecIsTriggerDisabled')
FROM [sys].[triggers] as TRIG 
inner join sys.tables as TAB 
on TRIG.parent_id = TAB.object_id 

或将其添加为where子句。

where TRIG.is_disabled = 0 -- or 1 depends on what you want

答案 1 :(得分:11)

SELECT *
FROM sys.triggers
WHERE is_disabled = 0

答案 2 :(得分:6)

SELECT 
       TAB.name as Table_Name
     , TRIG.name as Trigger_Name  
FROM [sys].[triggers] as TRIG
inner join sys.tables as TAB
on TRIG.parent_id = TAB.object_id

答案 3 :(得分:3)

SELECT 
    TAB.name as Table_Name,
    TRIG.name as Trigger_Name,
    Comments.Text TriggerText
FROM [sys].[triggers] as TRIG
    Inner Join sys.tables as TAB on TRIG.parent_id = TAB.object_id
    Inner Join syscomments Comments On TRIG.object_id = Comments.id
WHERE
    TRIG.is_disabled = 0;

是完整的解决方案

答案 4 :(得分:2)

select * from sys.triggers

此处object_id用于表格,因此加入sys.table即可获得表格名称

答案 5 :(得分:1)

您可以查询sys.triggers视图。

答案 6 :(得分:1)

select so.name, text
from sysobjects so, syscomments sc
where type = 'TR'
and so.id = sc.id
and text like '%related_table_name%'

答案 7 :(得分:0)

以下是对"数据库触发器"进行刷新时发生的查询。在SSMS。

SELECT
tr.name AS [Name],
'Server[@Name=' + quotename(CAST(
        serverproperty(N'Servername')
       AS sysname),'''') + ']' + '/Database[@Name=' + quotename(db_name(),'''') + ']' + '/DdlTrigger[@Name=' + quotename(tr.name,'''') + ']' AS [Urn],
tr.is_disabled AS [IsEnabled]
FROM
sys.triggers AS tr
WHERE
(tr.parent_class = 0)
ORDER BY
[Name] ASC

使用它,我创建了一个版本(增强了已接受的答案)以包含数据库触发器。

请注意左连接和COALESCE检查。

SELECT  
       COALESCE(TAB.name, 'DATABASE') as TargetObjectName
     , TRIG.name as Trigger_Name
     , TRIG.is_disabled  --or objectproperty(object_id('TriggerName'), 'ExecIsTriggerDisabled')
     -- select *
FROM [sys].[triggers] as TRIG 
left join sys.tables as TAB 
on TRIG.parent_id = TAB.object_id 
WHERE
/* (TRIG.parent_class = 0) and */
TRIG.is_disabled = 0

答案 8 :(得分:0)

//使用您的数据库

use [your_database_Name]

Select * from sys.triggers where is_disabled=0