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.
+3
A:
if object_id('FUNCTION_NAME') is not NULL
DROP FUNCTION <name>
You can also look the name up in sysobjects
IF EXISTS (SELECT *
FROM sysobjects
WHERE name='<function name>' and xtype='FN'
Actually, if the function could be a table function, you need to use
xtype in ('FN','TF')
Sparky
2010-02-18 17:39:54
+1 for a simple object_id use
gbn
2010-02-18 18:20:35
I've always preferred the Object_id method, it seems simpler to read in the code. Always curious why the Microsoft generated sample code uses the sys.objects lookup instead...
Sparky
2010-02-18 18:57:02
+5
A:
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
adrianbanks
2010-02-18 17:41:42
+1
A:
I usually shy away from queries from sys* type tables, vendors tend to change these between releases, major or otherwise. What I have always done is to issue the DROP FUNCTION <name>
statement and not worry about any SQL error that might come back. I consider that standard procedure in the DBA realm.
Jeff Walker
2010-02-18 17:42:54
sys. in SQL Server 2005 is the official way. They are *views* not tables nowadays and the actual sys tables are hidden from us.
gbn
2010-02-18 18:22:30
A:
IF EXISTS
(SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'functionName')
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION functionName
GO
Fiona Holder
2010-02-18 17:46:10