I have the following code list
Code Meaning
1 Single
2 Married/Separate
3 Divorced
4 Widowed
8 Not Applicable
99 Not known
I am trying to flatten these into a single row using a CTE. I have a CTE solution which uses RowNumber function to do this.
WITH Flattened (JoinItem, CodeMeaning) AS
(
SELECT 1 AS JoinItem, CAST('' AS VARCHAR(255))
UNION ALL
SELECT f.JoinItem+1, CAST(f.CodeMeaning + ',' + c.CodeMeaning AS VARCHAR(255))
FROM
(
SELECT JoinItem = ROW_NUMBER() OVER (ORDER BY Code),c.Code + ' - ' + c.Meaning AS CodeMeaning
FROM Codes c
) c
INNER JOIN Flattened f
ON f.JoinItem=c.JoinItem
)
SELECT TOP 1 JoinItem, CodeMeaning
FROM Flattened
ORDER BY JoinItem DESC
However, I'm wondering if I can do it without using the RowNumber function but still using a CTE. So I have the following - what I view as simpler - Sql
WITH Flattened (JoinItem, CodeMeaning) AS
(
SELECT 1 AS JoinItem, CAST('' AS VARCHAR(255))
UNION ALL
SELECT c.JoinItem, CAST(f.CodeMeaning + ',' + c.CodeMeaning AS VARCHAR(255))
FROM
(
SELECT 1 AS JoinItem,c.Code + ' - ' + c.Meaning AS CodeMeaning
FROM Codes c
) c
INNER JOIN Flattened f
ON f.JoinItem=c.JoinItem
)
SELECT JoinItem, odeMeaning
FROM Flattened
Now it is max-ing out on recursion and generating something like a cartesian join - if not worse!
I'm looking to try and get it to join to the anchor record each time using a fixed "JoinItem"
So any pointers to where I am going wrong would be helpful if there is a solution.
EDIT SqlFiddle