How to check if a function exists in a SQL database?
Solution 1:
This is what SSMS uses when you script using the DROP and CREATE
option
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[foo]')
AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
DROP FUNCTION [dbo].[foo]
GO
This approach to deploying changes means that you need to recreate all permissions on the object so you might consider ALTER
-ing if Exists instead.
Solution 2:
I tend to use the Information_Schema:
IF EXISTS ( SELECT 1
FROM Information_schema.Routines
WHERE Specific_schema = 'dbo'
AND specific_name = 'Foo'
AND Routine_Type = 'FUNCTION' )
for functions, and change Routine_Type
for stored procedures
IF EXISTS ( SELECT 1
FROM Information_schema.Routines
WHERE Specific_schema = 'dbo'
AND specific_name = 'Foo'
AND Routine_Type = 'PROCEDURE' )