I need some help with my t-sql code. Background I have a table that BY YEAR data output by columns. So a single row will have CN[Year 0]........CN[Year 10], Premiums[Year 0]......[Year 10] etc etc. I am trying to write a function that takes an integer parameter and then returns a table only for the specified year columns i.e CN, Premium etc etc. Ultimately I'd like to concatenate the tables at some point.I have the basics to run the code manually but unsure how to automate my function so it can return the table.
At the moment I can run the code within ------from here ------to here manually but not automate the code so it can return a table
CREATE FUNCTION [xxxxxxx_Price_Schema].get_MultiYear(@year varchar(1))
RETURNS TABLE
AS
RETURN
------from here
declare @year varchar(1);
declare @yearNo varchar(1);
declare @customerNo varchar(25);
declare @CN varchar(3);
declare @SQLString NVARCHAR(max);
declare @SQLResult nvarchar(max);
set @year = 1
set @yearNo = cast(@year as varchar(1))
set @customerNo = QUOTENAME(cast('CustomerNumber[Year '+ @yearNo + ']' as varchar(25)))
set @CN = concat('CN',@yearNo)
set @SQLString =
'
select distinct
[CN[Year '+ @yearNo +']]] AS CN
,[Premium[Year '+ @yearNo + ']]] AS Premium
,[Age[Year '+ @yearNo + ']]] AS Age
,[Sex[Year '+ @yearNo + ']]] AS Sex
FROM [Test].[Test202002].[PHL_MultiYear_Test_Output]
WHERE ' + @customerNo + ' = '''+ @CN + '''
'
EXECUTE sp_executesql @SQLString
----too here
RETURN @SQLString
END
GO

