I am facing the problem tree view to flat view, I have some data that has come from a tree, those are stored in a table that is presenting in my picture below left. I am saying the top level of tree is level1, and second level is level2 and so on. My expected result that is representing in my picture below right.

[![enter image description here](https://i.stack.imgur.com/NmebV.png)](https://i.stack.imgur.com/NmebV.png)

How can I convert my data to my expected result dynamically in SQL Server? We have to create dynamic column level1, level2, level3 and so on. Do you have any idea? Thanks.

Here is the sample data

```
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL 
DROP TABLE #TestData;

CREATE TABLE #TestData (
    Id INT NOT NULL,
    SomeName VARCHAR(3) NOT NULL,
    ParentId INT NULL 
    );
INSERT #TestData (Id, SomeName, ParentId) VALUES 
    (1, 'O', NULL),
    (2, 'D1', 1),
    (3, 'D2', 1),
    (4, 'S1', 2),
    (5, 'S2', 2),
    (6, 'S1', 3),
    (7, 'SP1', 3);

SELECT * FROM #TestData td;

```