I have this table:
create table Test (Value varchar(111))
insert Test select 'a,b,c'
I want to create a table valued function where I pass Test.Value and it returns the below table:
Where Value comes from Test table, and Item values are generated in this way: first item is whole value by itself (in example it consists of three comma-separated values), once there aren't any three comma-separated values, we go from left to right for two comma-separated values.
We go strictly from left to right, so there isn't any need for items like a,c or b,a. And then we go finally to one comma-separated value, which is a, b and c.
ItemLayer is just a layer which is being processed. Obviously, the separator should be a comma, and tvf should return Item and ItemLayer. I think the query should look something like this:
SELECT *
FROM Test t
CROSS JOIN fn_getItemsFromValues(t.Value) f
I think there should be some sort of a recursive CTE, but I can't figure it out how.
Here is an output if Value was 'a,b,c,d':
I'm using SQL Server 2017. I've tried this, but I'm stuck. Something is very off here.
DECLARE @data VARCHAR(100) = 'a,b,c'
;WITH CTE AS
(
SELECT @data TXT, LEFT(@data,1) Col1
UNION ALL
SELECT STUFF(TXT,1,1,'') TXT, LEFT(TXT,1) Col1 FROM CTE
WHERE LEN(TXT) > 0
)
select Col1,txt from CTE

