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)
 Category Search

Author  Topic 

sidharth.banyal
Starting Member

11 Posts

Posted - 2010-09-19 : 08:47:26
I have a category sub category table as:-

Catid
catname
parentcatid

parentcatid is foreign key to subcategories. It stores catid of parent category.

In my products table i am storing catid for category. Now when i am searching products, i need to show products whose category is child of any category.

EX:-

i have a category
CAT1
subcat1 is child of cat1
subcat2 is child of subcat1
then if i select cat1 then all products whether they are under cat1 subcat1 or subcat2 should display.

If i select sucat1 then all products under subcat1 osubcat2 should display.

Any help will be highly appreciated.

Thanks in advance.

Sidharth Banyal

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-09-19 : 11:31:40
you need to use common table expression for that. see the example below

http://msdn.microsoft.com/en-us/library/ms186243.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

sidharth.banyal
Starting Member

11 Posts

Posted - 2010-09-21 : 00:25:48
Pleas give me an example

Sidharth Banyal
Go to Top of Page

PavanKK
Starting Member

32 Posts

Posted - 2010-09-21 : 03:10:40
hi Sidharth,

The link provided by Visakh is having the required examples.
For your category search you can use the following query.

---

DECLARE @CatID VARCHAR(20)
SET @CatID = 'CAT1'

;WITH Cte AS
(
SELECT *
FROM Products
WHERE catid = @CatID

UNION ALL

SELECT P.*
FROM category C
JOIN Cte Ct ON C.parentcatid = Ct.Catid
JOIN Products P ON C.Catid = P.Catid
)

SELECT * FROM Cte

------


KK
Go to Top of Page
   

- Advertisement -