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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Query Help Need

Author  Topic 

CSK
Constraint Violating Yak Guru

489 Posts

Posted - 2008-04-24 : 16:06:36
Gurus,
I need a help to write a query.
here is the Scenario

TABLE NAME . PRODCUT

DECLARE @Product TABLE
(
ProductId CHAR(5),
CategoryId CHAR(5)
)

INSERT INTO @Product
SELECT 'P1','C1' UNION ALL SELECT 'P2','C2' UNION ALL SELECT 'P3','C3'

TABLE NAME . Category

DECLARE @Category TABLE
(
categoryid CHAR(5),
parentcategoryid CHAR(5)
)
INSERT INTO @Category
SELECT 'C1','C2' UNION ALL SELECT 'C2','C3' UNION ALL SELECT 'C3',NULL

I want query that

product their category and then their all parents.

if c1 is my category i want to know their parents.

o/p

p1,c1,c2,c3,null


any one help me to write this query..

Thanks
-- csk

ganeshkumar08
Posting Yak Master

187 Posts

Posted - 2008-04-25 : 02:39:07
Hello,

select p.ProductId,p.CategoryId,c.parentcategoryid,c1.parentcategoryid,c2.parentcategoryid--,c3.parentcategoryid
from @Product p
inner join @Category c on p.CategoryId=c.categoryid
inner join @Category c1 on c1.CategoryId =c.parentcategoryid
inner join @Category c2 on c2.CategoryId =c1.parentcategoryid
--inner join @Category c3 on c3.CategoryId =c1.parentcategoryid

Execute the above query
You will get the exact result

Ganesh
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-04-25 : 03:38:09
And if your hierarchy level is not static use recursive CTE to get your result
Go to Top of Page
   

- Advertisement -