I have a Categories table and Items table like these:
Categories
CategoryID CategoryName CategoryLevel OrdinalNumber 1 All 0 1 2 iOS 1 2 3 Android 1 5 4 Sub iOS 1 2 3 5 Sub Andoid 1 2 6 6 Others 1 8 7 Sub Andoid 2 2 7 8 Sub iOS 2 2 4
Items
ItemID ItemName CategoryID 1 iPhone 5 4 2 Motorola Droid 5 3 iPad 2 8 4 Samsung S1 7 5 iPhone 4 4 6 iPad Air 8 7 Samsung S3 7 8 Dell Laptop 6
As you can see, they can be join by CategoryID. The Categories table, if sorted by OrdinalNumber and CategoryLevel, has tree-view display:
CategoryID CategoryName CategoryLevel OrdinalNumber 1 All 0 1 2 iOS 1 2 4 Sub iOS 1 2 3 8 Sub iOS 2 2 4 3 Android 1 5 5 Sub Andoid 1 2 6 7 Sub Andoid 2 2 7 6 Others 1 8Now I need an SQL command that can display all items belong to a category and its subcategories. For example, if I choose CategoryID=2 I will get:
iPhone 5
iPad 2
iPhone 4
iPad Air
If I choose CategoryID=3 I will get:
Motorola Droid
Samsung S1
Samsung S3
If I choose CategoryID=6 I will get:
Dell Laptop
And if I choose CategoryID=1 I will get all items. I am thinking of using Common Table Expression but can not figure out how to do it.