检查SQL Server中是否存在触发器的最简便方法是什么? [英] What is the most portable way to check whether a trigger exists in SQL Server?
问题描述
我正在寻找最可移植的方法来检查MS SQL Server中是否存在触发器。它至少需要在SQL Server 2000、2005和2008上才能运行。
I'm looking for the most portable method to check for existence of a trigger in MS SQL Server. It needs to work on at least SQL Server 2000, 2005 and preferably 2008.
该信息似乎不在INFORMATION_SCHEMA中,但是如果它在某处,我宁愿从那里使用它。
The information does not appear to be in INFORMATION_SCHEMA, but if it is in there somewhere, I would prefer to use it from there.
我确实知道这种方法:
if exists (
select * from dbo.sysobjects
where name = 'MyTrigger'
and OBJECTPROPERTY(id, 'IsTrigger') = 1
)
begin
end
但我不确定它是否适用所有SQL Server版本。
But I'm not sure whether it works on all SQL Server versions.
推荐答案
这适用于SQL Server 2000及更高版本
This works on SQL Server 2000 and above
IF OBJECTPROPERTY(OBJECT_ID('{your_trigger}'), 'IsTrigger') = 1
BEGIN
...
END
请注意,幼稚的对话不能可靠地起作用:
Note that the naive converse doesn't work reliably:
-- This doesn't work for checking for absense
IF OBJECTPROPERTY(OBJECT_ID('{your_trigger}'), 'IsTrigger') <> 1
BEGIN
...
END
...因为如果对象根本不存在, OBJECTPROPERTY
返回 NULL
和 NULL
当然不是<> 1
(或其他任何东西)。
...because if the object doesn't exist at all, OBJECTPROPERTY
returns NULL
, and NULL
is (of course) not <> 1
(or anything else).
在SQL Server 2005或更高版本上,您可以使用 COALESCE
进行处理,但是如果需要支持SQL Server 2000,则必须构造语句来处理三个可能的返回值: NULL
(该对象根本不存在), 0
(它存在但不是触发器)或 1
(这是一个触发器)。
On SQL Server 2005 or later, you could use COALESCE
to deal with that, but if you need to support SQL Server 2000, you'll have to structure your statement to deal with the three possible return values: NULL
(the object doesn't exist at all), 0
(it exists but is not a trigger), or 1
(it's a trigger).
这篇关于检查SQL Server中是否存在触发器的最简便方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!