title: Error:create function must be the only statement in the batch
body: <p>I am trying to firstly check if the function exists then create it, if it doesn't exist.</p>
  
  <p>I'm getting this error from the function:</p>
  
  <pre><code>IF NOT EXISTS (SELECT * FROM sys.objects 
      WHERE object_id = OBJECT_ID(N'[dbo].[GetRelativeExpiry]') AND type in (N'U'))
      BEGIN
  
      SET ANSI_NULLS ON
      SET QUOTED_IDENTIFIER ON
  
      CREATE FUNCTION [dbo].[GetRelativeExpiry]
      (
          @Date DATE,
          @N INT
      )
      RETURNS DATE
      AS
      BEGIN
          -- Declare the return variable here
          DECLARE @Expiry as DATE;
  
          IF @N &gt; 0
          BEGIN
              SELECT @Expiry = MAX(E2.Expiry) 
              FROM (SELECT TOP(@N) Expiry
                    FROM ExpiryDates E1
                    WHERE E1.Expiry &gt;= @date
                    ORDER BY E1.Expiry) AS E2
          END
          ELSE
          BEGIN
              SELECT @Expiry = MIN(E2.Expiry) 
              FROM (SELECT TOP(-@N) Expiry
                    FROM ExpiryDates E1
                    WHERE E1.Expiry &lt;= @date
                    ORDER BY E1.Expiry DESC) AS E2
          END
          RETURN @Expiry
  
      END
  
      END
  </code></pre>
  
  <p>I am not sure why I am getting this error, could someone please help?
  I am using Microsoft SQL Server Management Studio 2014</p>