检查 SQL Server 中是否存在触发器的最便携方法是什么?

2022-01-01 00:00:00 sql-server triggers information-schema

我正在寻找最便携的方法来检查 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).

相关文章