确保如果类别不存在关键字,则应返回其父级的数据

时间:2016-03-03 07:18:44

标签: sql sql-server sql-server-2008

Sample Data

示例输入/输出:

Input: 202
Output: ParentCategoryID = 201
        Name = Operating System
        Keywords = Teaching

这是我尝试过的:

 SELECT TOP 1000 T1.[CatergoryId]
  ,T1.[ParentCategoryId]
  ,T1.[Name]
  ,(case when T1.[Keywords] IS null 
   then (select C.[Keywords] FROM [Ingenio].[dbo].[Cat] C 
         where c.[CatergoryId]=T1.[ParentCategoryId])
   else T1.[Keywords] 
   end) as Keywords 
 FROM [Ingenio].[dbo].[Cat] T1  
 join [Ingenio].[dbo].[Cat] T2  
 on T1.CatergoryId =T2.CatergoryId  
 where T1.CatergoryId = 202

查询适用于第1级,但不适用于第2级和第n级。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

您必须使用Recursive CTE

DECLARE @param INT = 201

;WITH CTE AS (
   SELECT CategoryId, ParentCategoryId, Name, Keywords
   FROM Cat
   WHERE CategoryId = @param

   UNION ALL

   SELECT c1.CategoryId, c1.ParentCategoryId, c1.Name, c1.Keywords
   FROM Cat AS c1
   INNER JOIN CTE AS c2 ON c1.CategoryId = c2.ParentCategoryId  
   WHERE c1.Keywords IS NOT NULL -- terminate if keyword from previous level is not null
)
SELECT *
FROM CTE

<强>输出:

CategoryId  ParentCategoryId    Name        Keywords
------------------------------------------------------
201         200                 Computer    NULL
200         -1                  tutoring    teaching