Question

I guys,
I have a Category table with CategoryID (primary key), ParentID (int not null) and Category (nvarchar not null).
I´m trying to insert and retrieve in this table Categories with ID CategoryID and SubCategories with ID ParentID.
I´ve been trying the whole week-end with no luck, and hope you can help me. I´m using MSSQL 2008.
The table structure should look like this:

-Category1          
        SubCategory1  
        SubCategory2  
    ...  

-Category2  
            SubCategory2  
            SubCategory2  
    ...  

Any help will be very appreciated

Was it helpful?

Solution

Check for Common Table Expressions, those allow you to create "recursive-selects". http://www.mssqltips.com/sqlservertip/1520/recursive-queries-using-common-table-expressions-cte-in-sql-server/

OTHER TIPS

You can use a recursive common table expression:

WITH cteTable(madeUpColA, madeUpColB, Etc) as
(
   -- this select statement with the union all is what does the recursive query
   SELECT aCol as madeUpColA, bCol as madeUpColB, Etc
   from dbo.someTable
   UNION ALL
   SELECT aCol as madeUpColA, bCol as madeUpColB, Etc
   FROM dbo.someTable st
   INNER JOIN cteTable as c -- inner join on relationship
   ON st.aCol = c.madeUpColA
)
-- this select statement is what retrieves the data from the above query
SELECT madeUpColA, madeUpColB, Etc
FROM cteTable
-- add your other criteria here

You can use MSDN documentation for the WITH statement to specialize your query

Are you just looking for a simple self join? If so, this should work:

select parent.category, subcat.category as subcategory
from Category subcat join
     Category parent
     on subscat.parentid = parent.categoryid

Or do you need to traverse a whole chain of parents? If so, then the recursive CTE is the better approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top