Friday, February 26, 2010

Recursion in sql stored procedure

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[uspGetCardsByCatID] (@catId int)
as
BEGIN
/*Recursion*/
with RecursionCTE (iCategoryId_PK,iParentCategoryId_FK,sTitle, bIsActive)
as
(
select *
from vwCategory
where iParentCategoryId_FK = @catId and bIsActive = 1
union all
select R1.*
from vwCategory as R1
join RecursionCTE as R2 on R1.iParentCategoryId_FK = R2.iCategoryId_PK
)
/*End Recusion*/
Select * from dbo.vwCard where iCategoryId_FK = @catId or iCategoryId_FK in (select iCategoryId_PK from RecursionCTE) order by (iTotalCustomizeOrders + iTotalBlankOrders) DESC
END

No comments:

Post a Comment