I have the following script in SQL Server 2014 for creating a scalar function named GetFiscalPeriod. The script must check for the existence of the function by its name before creating it.
USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (select * from dbo.sysobjects where
id = object_id(N'[dbo].[GetFiscalPeriod]')
and OBJECTPROPERTY(id, N'IsScalarFunction') = 1)
--want to terminate the whole batch
RETURN --doesn't work the way I want
--seems to terminate IF batch only
GO
CREATE FUNCTION [dbo].[GetFiscalPeriod] ()
Returns INT
AS
BEGIN
RETURN (select MAX(Id) from dbo.__FiscalPeriod__);
END
I want it to terminate the whole thing as it reaches inside IF body. (RETURN)
The problem is no matter how I change the code, either it jumps to CREATE FUNCTION giving this error:
There is already an object named 'GetFiscalPeriod' in the database.
Or giving this syntax error (when I try to put CREATE FUNCTION in the IF clause):
'CREATE FUNCTION' must be the first statement in a query batch.
Question is:
Is there anyway to tell SQL to ignore the rest of the script when the object name exists?
Note:
I used to drop the function beforehand, and it works. But I don't want to drop and recreate everything every time.
...
IF EXISTS (select * from dbo.sysobjects where
id = object_id(N'[dbo].[GetFiscalPeriod]')
and OBJECTPROPERTY(id, N'IsScalarFunction') = 1)
DROP FUNCTION [dbo].[GetFiscalPeriod] --works
GO
CREATE FUNCTION [dbo].[GetFiscalPeriod] ()
...
sp_executesqlGOseparators).