What is the most portable way to check whether a trigger exists in SQL Server?(检查 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 中是否存在触发器的最便携方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查 SQL Server 中是否存在触发器的最便携方法是什么?


基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带更新的 sqlite CTE 2022-01-01