我已經完成了下面的CTE它工作正常,但我需要得到最後一個節點的總和,所以問題是當我添加T1.Debit列計算其給我一個無效的列名稱'借記'!在線***Sql遞歸錯誤無效列名CTE
ALTER Function [dbo].[SubTopics_GetSum]
-- Add the parameters for the stored procedure here
(
@TopicID int
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
WITH cte
AS (
SELECT
T1.TopicID,
T1.Code,
T1.Description,
T1.ParentID,
T1.ParentID AS NewParentID,
CAST(T1.Code AS nvarchar(MAX)) AS TopicCode,
CAST(T1.Description AS nvarchar(MAX)) AS TopicDescription,
isnull((Accounting.DocumentDetail.Debit),0) AS Debit,
isnull((Accounting.DocumentDetail.Credit),0) AS Credit
FROM Accounting.Topics AS T1
LEFT OUTER JOIN Accounting.DocumentDetail
ON T1.TopicID = Accounting.DocumentDetail.TopicFK
where NOT EXISTS(
SELECT
T2.TopicID,
T2.Code,
T2.Description,
T2.ParentID,
isnull((Accounting.DocumentDetail.Debit),0) AS Debit,
isnull((Accounting.DocumentDetail.Credit),0) AS Credit
FROM Accounting.Topics AS T2
LEFT OUTER JOIN Accounting.DocumentDetail
ON T2.TopicID = Accounting.DocumentDetail.TopicFK
WHERE (ParentID = T1.TopicID)
)
UNION ALL
SELECT
c.TopicID,
c.Code,
c.Description,
c.ParentID,
T1.ParentID AS NewParentID,
CAST(T1.Code AS nvarchar(MAX)) + c.TopicCode AS TopicCode,
CAST(T1.Description AS nvarchar(MAX)) + ' - ' + c.TopicDescription AS TopicDescription,
*** isnull((T1.Debit),0)+isnull(c.Debit,0) AS Debit,--IN THIS LINE error 'Invalid Column Name 'Debit''
isnull(c.Credit,0) AS Credit
FROM cte AS c
INNER JOIN Accounting.Topics AS T1
ON T1.TopicID = c.NewParentID
)
SELECT isnull(sum(Debit),0)AS Debit,
isnull(sum(Credit),0)AS Credit
FROM cte AS c
WHERE (NewParentID = @TopicID)
)
讓我知道什麼是錯的,我的代碼混淆了!!!
實際上它不會返回我最後一個節點的借方,貸方...總和! 檢查以下PIC
對於幫助我們找到可以很好的格式化代碼行。 –