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
 self join

Author  Topic 

mr_dayal
Starting Member

37 Posts

Posted - 2008-08-21 : 10:06:51
I have a table category_master with following fileds

cat_id(pk), cat_name,cat_parent_id

This table is storing categories where one category may fall under some other category which is handled by cat_parent_id.
I want a self join so that tha data looks like this.

cat_id cat_name cat_parent_id cat_parent_name
1 Computers null null
2 scanners 1 Computers
3 printers 1 computers
4 harddisk 1 computers
5 internalhdd 4 harddisk
6 externalhdd 4 harddisk


so on..
What will be the query..

Mr Dayal

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-08-21 : 10:10:43
Are you using sql 2005?
Go to Top of Page

mr_dayal
Starting Member

37 Posts

Posted - 2008-08-21 : 10:13:00
yes, 2005 express Edition

Mr Dayal
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-08-21 : 10:14:34
if sql 2005 use recursive cte approach like below
;
With Category_CTE (CatID,CatName,ParentID,ParentName)AS
(
SELECT cat_id, cat_name, cat_parent_id, cat_parent_name
FROM YourTable
WHERE cat_parent_id IS NULL
UNION ALL
SELECT c.CatID,c.CatName,c.ParentID,c.ParentName
FROM YourTable t
INNER JOIN Category_CTE c
ON c.CatID=t.cat_parent_id
)

SELECT * FROM Category_CTE




and if sql 2000 refer below link

http://support.microsoft.com/kb/248915
Go to Top of Page

mr_dayal
Starting Member

37 Posts

Posted - 2008-08-21 : 10:23:58
It's not working ,I have Only three columns in my table

Mr Dayal
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-08-21 : 10:26:52
modify like this
;
With Category_CTE (CatID,CatName,ParentID,ParentName)AS
(
SELECT cat_id, cat_name, NULL, NULL
FROM YourTable
WHERE cat_parent_id IS NULL
UNION ALL
SELECT t.cat_id,t.cat_name,c.CatID,c.CatName
FROM YourTable t
INNER JOIN Category_CTE c
ON c.CatID=t.cat_parent_id
)

SELECT * FROM Category_CTE
Go to Top of Page
   

- Advertisement -