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 "Incorrect syntax near Begin, declare expecting (.", "Must declare the scalar variable @policybillid" and in the end of the function "Incorrect syntax near ')'.". Any help would be appreciated.
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 "@policybillid".
order by cuoteID
select * from @expiresDates
declare @diffMonth int
declare @quota varchar(max) = ''
if((select count(*) from @expiresDates) > 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 ')'.***