0

I have table with fruits and their sub types. I need to make a sql VIEW from data in that table as a hierarchical tree.

So the output I need is looks like this.

fruits

My current query gives output in single column. But I need to show output in separate columns as shown in above image.

My query: SQL fiddle

WITH items AS (
    SELECT FRUIT_ID, FRUIT_NAME
    , 0 AS Level
    , CAST(FRUIT_NAME AS VARCHAR(255)) AS Path
    FROM FRUIT 
    WHERE PARENT_FRUIT = '0' AND FRUIT_ID = 'FR01'

    UNION ALL

    SELECT i.FRUIT_ID, i.FRUIT_NAME
    , Level + 1
  , CAST(Path + ' => ' + CAST(i.FRUIT_NAME AS VARCHAR(255)) AS VARCHAR(255))
    FROM FRUIT i
    INNER JOIN items itms ON itms.FRUIT_ID = i.PARENT_FRUIT
)

SELECT * FROM items ORDER BY Path

I am using Microsoft SQL Server 2014 - 12.0.2000.8 (X64)

Bishan
  • 15,211
  • 52
  • 164
  • 258

0 Answers0