Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Parent ID of Table

$
0
0

Hi all,

DECLARE @BaseLevel1 TABLE (
ID INT,
Level1Category Nvarchar(20)
)

DECLARE @BaseLevel2 TABLE (
ID INT,
BaseLevel1 INT,
Level2Category Nvarchar(20)
)

INSERT INTO @BaseLevel1 VALUES (1, 'Alpha')
INSERT INTO @BaseLevel1 VALUES (2, 'Kemel')
INSERT INTO @BaseLevel1 VALUES (3, 'Vector')

INSERT INTO @BaseLevel2 VALUES (1, 1,  'Rg1')
INSERT INTO @BaseLevel2 VALUES (2, 1,  'Gh1')
INSERT INTO @BaseLevel2 VALUES (3, 2, 'Fg1')
INSERT INTO @BaseLevel2 VALUES (4, 3, 'Df21')
INSERT INTO @BaseLevel2 VALUES (5, 3, 'As2')

SELECT * FROM @BaseLevel1
SELECT * FROM @BaseLevel2

What I would like is to somehow join the tables to result in the following table. Notice Alpha, Kemel and Vector are in BaseLevel1 Table so they have no parent ID so in the column ParentID it will be null. But the other data ie Rg1, Gh1 etc are in BaseLevel2 table and have a column called BaselLeve1 which references the ID of their parent in BaseLevel2 table. So this should have the relevant IDs. Also would like a new column just to have unique ID per row.  

Is the below possible?

NewID  LevelCategory   ParentID 
1           Alpha              NULL
2           Kemel             NULL
3           Vector            NULL
4           Rg1                1
5           Gh1               1
6           Fg1                2
7           Df21              3
8           As2               3


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>