如何将CTE用于IN子句?

时间:2014-04-12 04:49:24

标签: sql-server common-table-expression

我希望得到我所有类别的所有孩子并与内容合并。 我希望当我点击一个类别时,显示所有类别和子类别的内容。 我使用CTE,它是:

WITH ret AS (SELECT     id, parent
                         FROM        ContentsGroups
                         WHERE     (id = @id)
                         UNION ALL
                         SELECT     t.id, t.parent
                         FROM         ContentsGroups AS t INNER JOIN
                                               ret AS r ON t.parent = r.id)
SELECT     id
 FROM         ret

如何将输出连接到我的目录表?

当我使用这些时:

SELECT title FROM Contents WHERE id IN (WITH ret AS ... )

我得到与条款有关的错误 我如何与我的表合并条款? 感谢

1 个答案:

答案 0 :(得分:2)

试试这个

WITH ret AS (SELECT     id, parent
                         FROM        ContentsGroups
                         WHERE     (id = @id)
                         UNION ALL
                         SELECT     t.id, t.parent
                         FROM         ContentsGroups AS t INNER JOIN
                                               ret AS r ON t.parent = r.id)

SELECT title FROM Contents WHERE id IN (SELECT id FROM ret);