递归SQL查询(可空子)

时间:2017-01-10 23:10:09

标签: sql sql-server recursion

我一直在为我的推荐程序进行递归SQL查询,但是我取得了很好的成功,但是我试图解决一个问题。我有一个父/子关系,在下面的表格架构中定义:

  • Id(PK,UniqueIdentifier,Not Null)
  • ReferrerMemberId(FK,uniqueidentifier,not null)
  • ReferreeEmail(nvarchar(256,not null)
  • ReferreeFirstName(nvarchar(50),not null)
  • ReferreeMemberId(FK,uniqueidentifier,null)
  • DateRedeemed(datetime,null)

这个数据库表的设计是没有ReferreeMemberId(即null)然后我想显示与null数据的子关系。下面的SQL查询仅显示ReferreeMemberId为NOT NULL的子元素。如果我可以得到一些帮助来修改下面的SQL,将不胜感激。因此,我想显示“不完整”推荐的记录,即存在空 referreememberid dateredeemed 也为空。

尝试执行外部查询或离开外部查询时,我收到以下错误:

递归公用表表达式'HierarchyTraaversal'的递归部分不允许外连接。

    DECLARE @TopLevel INT = 1    -- Top level manager (node)
    ,@NumLevels   INT = 10;   -- Depth of the hiearchy to traverse

WITH HierarchyTraaversal AS
(
    -- rCTE anchor: retrieve the top level node
    SELECT [Level]=1, a.DateRedeemed, a.ReferrerMemberId, u.FirstName + ' ' + u.LastName as Referrer, u.PhotoUrl as ReferrerPhotoUrl, a.ReferreeMemberId, ub.FirstName + ' ' + ub.LastName as Referree, ub.PhotoUrl as ReferreePhotoUrl
        ,ReferrerReferree=CAST(ReferrerMemberId AS VARCHAR(8000)) + '/' + CAST(ReferreeMemberId AS VARCHAR(8000))
    FROM dbo.Referrals as a
    JOIN Member as m on a.ReferrerMemberId = m.Id
    JOIN Member as mb on a.ReferreeMemberId = mb.Id
    JOIN AspNetUsers as u on m.AspNetUserId = u.Id
    JOIN AspNetUsers as ub on mb.AspNetUserId = ub.Id
    WHERE ReferrerMemberId = '914A67C8-476D-E511-9BDC-14DAE91525CD'


    UNION ALL

    -- rCTE recursion: retrieve the following nodes
    SELECT [Level]+1, a.DateRedeemed,a.ReferrerMemberId, u.FirstName + ' ' + u.LastName as Referrer, u.PhotoUrl as ReferrerPhotoUrl, a.ReferreeMemberId, ub.FirstName + ' ' + ub.LastName as Referree, ub.PhotoUrl as ReferreePhotoUrl
        ,ReferrerReferree=ReferrerReferree + '/' + CAST(a.ReferreeMemberId AS VARCHAR(8000))
    FROM dbo.Referrals a
    JOIN HierarchyTraaversal b ON b.ReferreeMemberId = a.ReferrerMemberId
    JOIN Member as m on a.ReferrerMemberId = m.Id
    JOIN Member as mb on a.ReferreeMemberId = mb.Id
    JOIN AspNetUsers as u on m.AspNetUserId = u.Id
    JOIN AspNetUsers as ub on mb.AspNetUserId = ub.Id
    WHERE [Level] < @NumLevels --+ 1

)
SELECT [Level], DateRedeemed, ReferrerMemberId, Referrer, ReferrerPhotoUrl, ReferreeMemberId, ReferrerReferree, Referree, ReferreePhotoUrl
FROM HierarchyTraaversal
ORDER BY [Level], ReferrerMemberId, ReferreeMemberId; 

0 个答案:

没有答案