What is the most portable way to check whether a trigger exists in SQL Server?

后端 未结 9 1773
醉酒成梦
醉酒成梦 2020-12-14 05:50

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 prefe

9条回答
  •  萌比男神i
    2020-12-14 06:15

    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
    

    ...because if the object doesn't exist at all, OBJECTPROPERTY returns NULL, and NULL is (of course) not <> 1 (or anything else).

    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).

提交回复
热议问题