title: Multiple errors in SQL Server Function
body: <p>I'm trying to make a function that evaluates the expiration date in a policy and based on that when is called in a Query it returns the text values ('Monthly'..and so on). but i'm getting a few errors of type &quot;Incorrect syntax near Begin, declare expecting (.&quot;, &quot;Must declare the scalar variable @policybillid&quot; and in the end of the function &quot;Incorrect syntax near ')'.&quot;. Any help would be appreciated.</p>
  <pre><code>USE [defaultDB]
  GO
  
  SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  CREATE OR ALTER FUNCTION [dbo].[fn_Payment_GetPaymentCoutesByPaymentID]( @policybillid BIGINT, @companyID BIGINT) Returns TABLE
  AS
  RETURN (
  BEGIN( ***Incorrect syntax near 'BEGIN'.  Expecting '(', SELECT, or WITH.***
      declare @expiresDates as table(expiredOn date) ***Incorrect syntax near 'declare'.***  Expecting '(', or SELECT.
  
  insert into @expiresDates
  select top(2) expiredOn from PolicyPaymentPlan 
  left join PolicyPaymentPlanFee on PolicyPaymentPlan.paymentPlanID= PolicyPaymentPlanFee.paymentPlanID
  where PolicyPaymentPlan.policyBillID = @policybillid --Must declare the scalar variable &quot;@policybillid&quot;.
  order by cuoteID
  
  select * from @expiresDates
  declare @diffMonth int
  declare @quota varchar(max) = ''
  
  if((select count(*) from @expiresDates) &gt; 1)
  BEGIN
        set @diffMonth = DATEDIFF(month, (select top(1) expiredOn from @expiresDates),  (select top(1) expiredOn from @expiresDates order by expiredOn desc));       
        set @quota = ( SELECT 
        CASE 
              WHEN @diffMonth =1 
              then 
                     'Monthly'
              WHEN @diffMonth =2 THEN 
                    'bimonthly'
              WHEN @diffMonth =3 THEN 
                    'trimonthly '
              WHEN @diffMonth =4 THEN
                     'Four-Monthly'
              WHEN @diffMonth =6 THEN
                     'biannual'
              ELSE 'Cash' 
              END      
        )     
  END
  ) ***Incorrect syntax near ')'.***
  
  </code></pre>