Search code examples
t-sqlsql-server-2000

How do I drop a function if it already exists?


I know this must be simple, but how do I preface the creation of a function with a check to see if it already exists? If it exists, I want to drop and re-create it.


Solution

  • IF EXISTS (
        SELECT * FROM sysobjects WHERE id = object_id(N'function_name') 
        AND xtype IN (N'FN', N'IF', N'TF')
    )
        DROP FUNCTION function_name
    GO
    

    If you want to avoid the sys* tables, you could instead do (from here in example A):

    IF object_id(N'function_name', N'FN') IS NOT NULL
        DROP FUNCTION function_name
    GO
    

    The main thing to catch is what type of function you are trying to delete (denoted in the top sql by FN, IF and TF):

    • FN = Scalar Function
    • IF = Inlined Table Function
    • TF = Table Function