Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 denormalizing the table

Author  Topic 

Naveensrcl
Starting Member

8 Posts

Posted - 2013-08-08 : 00:23:25
Hi Experts,

I need to denormalizing the below table:

CREATE TABLE #temp
(
Id int
,category int
,Parent_id int
,Lvl tinyint
,Name varchar(20)
)

insert into #temp
SELECT 1,1,null,1,'World' UNION ALL
SELECT 2,1,1,2,'Asia' UNION ALL
SELECT 3,1,2,3,'India' UNION ALL
SELECT 4,2,null,1,'a' UNION ALL
SELECT 5,2,null,1,'d' UNION ALL
SELECT 6,2,5,2,'dd' UNION ALL
SELECT 7,2,4,2,'aa' UNION ALL
SELECT 8,2,7,3,'aaa' UNION ALL
SELECT 9,2,6,3,'ddd' UNION ALL
SELECT 10,2,9,4,'dddd' UNION ALL
SELECT 11,2,8,4,'aaaa' UNION ALL
SELECT 12,2,8,4,'bbbb' UNION ALL
SELECT 13,2,8,4,'cccc' UNION ALL
SELECT 14,1,2,3,'china'

--Expected Output:
Id category Level1_id Level1_Name Level2_id Level2_Name Level3_id Level3_Name Level4_id Level4_Name Level5_id Level5_Name
1 1 1 World 2 Asia 14 china NULL NULL NULL NULL
2 1 1 World 2 Asia 3 India NULL NULL NULL NULL
3 2 4 a 7 aa 8 aaa 11 aaaa NULL NULL
4 2 4 a 7 aa 8 aaa 12 bbbb NULL NULL
5 2 4 a 7 aa 8 aaa 13 cccc NULL NULL
6 2 5 d 6 dd 9 ddd 10 dddd NULL NULL




Currenlty I am achieving this with joins .. but there could be a better way to do this.

Thanks!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-08-08 : 01:01:43
You need to use recursive CTEs for that
See
http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -