Saturday, November 19, 2011

SQL Server - Check to see if a function already exists

So, you need to know if a function already exists in your database?  The code you seek is below.  

Need to know how to create that function as well?  I've created a useless function just for you.

-------------------------------------------------
-- Does the function already exist?
-- if so... drop it.







--
--
-- This will check for the various types of functions
-- Type of:
--   FN = Scalar Function
--   IF = Inline Table Function
--   TF = Table Function
--
-- If you are working with Assembly CLR Functions then you will
-- need to use:
--
--   FS = Assembly (CLR) Scalar Function
--   FT = Assembly (CLR) Table Valued Function
--
-------------------------------------------------IF  EXISTS
    (
        SELECT *
            FROM sys.objects
            WHERE object_id = OBJECT_ID(N'dbo.
xTestFunction')
            AND type in (N'FN', N'IF', N'TF')
    )

  BEGIN
   PRINT 'function found... Dropping'
   DROP FUNCTION dbo.xTestFunction
  END

ELSE
  BEGIN
    PRINT 'function does not yet exist...'
  END

GO

-------------------------------------------------
--Create a useless Test Function
-- Pass in a text string
-- Get the same text string back
-------------------------------------------------
CREATE FUNCTION dbo.xTestFunction( @Input NVarChar(MAX) )

RETURNS NVarChar(MAX)
AS

BEGIN
    DECLARE @Result NVarChar(MAX)

    SET @Result = @Input
  
    RETURN @Result
END

GO


-------------------------------------------------
--Now we will check to see if the code works
-------------------------------------------------
Select dbo.xTestFunction('This is my useless text string Input')






No comments:

Post a Comment