> On 18 Apr 2022, at 11:56, Pól Ua Laoínecháin <[email protected]> wrote:
(…) > All of the code below is available on the fiddle here: > > https://dbfiddle.uk/?rdbms=postgres_13&fiddle=0cc20c9081867131260e6e3550bd08ab (…) > OK, grand, now I wish to perform a RECURSIVE CTE on it. So, I start by > trying something (I thought was) very simple. Obviously, I plan to do > more, but I wanted to get the "mechanics" correct to start with. So, > my query is: > > WITH RECURSIVE cte1 (n, ln) AS > ( > SELECT 1 AS n, string > FROM line Here is your first problem, this will yield a result for each row in your line table, numbering it ‘1’. You seem to have expected just a single result here, but that is something that you need to take care of in your query. This part is called the base case, base step or initial step. > UNION ALL > SELECT n + 1, ln > FROM cte1 > WHERE n < (SELECT COUNT(*) FROM line) And then for each of those rows, it will add all those rows (from the same CTE!) again. This part is called the recursive step. You did add a termination condition here, which indeed manages to terminate, but it does so too late. It seems that you do understand some of the concepts of recursive CTE’s, but you appear to be missing some crucial knowledge. For example, it is actually possible to query multiple trees with a single recursive CTE. It is not limited to a single tree. How many trees the CTE will navigate depends on how you selected the rows in the base case. > ) > SELECT * FROM cte1; > > i.e. have a counter variable and a string from the line table My first question is why you’re using a recursive CTE here? This doesn’t appear to be hierarchical data (such as a tree), unless perhaps you intended to actually traverse the HTML document hierarchy? > > But, then to my horror, the result of this query is > > 1with t(x) as (values( XMLPARSE(DOCUMENT > ('<root><NotificationServiceDetails NotificationNo="0" > AlarmCode="mail" AlarmStartTime="10:00:00" AlarmTime="0" Id ="2" >> <NotificationServiceDetail > Id="2"><Title><![CDATA[aaaaaaaaaaaaa]]></Title><ContentJson><