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 中是否存在触发器的最便携方法是什么?
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
