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 中是否存在触发器的最便携方法是什么?
基础教程推荐
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在多列上分布任意行 2021-01-01
