带有case语句的SQL Server 2008视图错误

时间:2011-11-22 19:19:25

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

我无法弄清楚为什么这段代码作为查询执行,但是当我在视图中执行它时,它会抛出一个多部分标识符无法绑定,错误。

当我取出case语句时它在视图中起作用,所以我认为它与case语句有关。

任何建议都表示赞赏。

WITH [cteFrostSum] AS
(
    SELECT ID AS ID, theMonth  as Mo,
    SUM(dbo.Frost.[DRAmount])  AS [DRAmount]
    FROM dbo.Frost 
    GROUP BY [ID], theMonth
) 
SELECT DISTINCT 
    TOP (100) PERCENT      
    dbo.ternean.MemberID, 
    dbo.ternean.SSN, 
    dbo.ternean.GroupName, 
    dbo.ternean.CustomerID, 
    dbo.ternean.GroupNumber, 
    dbo.ternean.LastName, 
    dbo.Frost.DRAmount, 
    dbo.Frost.HittheBank, 
    dbo.Frost.MonthofPremium, 
    cte.[DRAmount] AS [SUM_Frost_Balance],
    dbo.ternean.TotalCost,
    cte.[DRAmount] - dbo.ternean.TotalCost AS Diff,
    dbo.ternean.ACH_RoutingNo, 
    dbo.Frost.RTNum, 
    dbo.ternean.ACH_AcctNo,
    dbo.Frost.AccountNumber, 

    CASE
        WHEN dbo.Frost.RTNum <> SUBSTRING(dbo.ternean.ACH_RoutingNo, 2, 20)
            THEN 'DO not match'
        WHEN dbo.Frost.RTNum = SUBSTRING(dbo.ternean.ACH_RoutingNo, 2, 20)
            THEN 'match'
    END AS [Routing # match], 
    CASE
        WHEN SUBSTRING(dbo.ternean.ACH_AcctNo, 2, 20) <> dbo.Frost.AccountNumber
            THEN 'DO not match'
        WHEN SUBSTRING(dbo.ternean.ACH_AcctNo, 2, 20) = dbo.Frost.AccountNumber
            THEN 'match'
    END AS [Account # match],
    dbo.Frost.theMonth
FROM dbo.Frost
INNER JOIN dbo.ternean ON dbo.Frost.ID = dbo.ternean.CustomerID
    AND dbo.Frost.theMonth = dbo.ternean.theMonth 
INNER JOIN [cteFrostSum] cte ON dbo.Frost.ID = cte.ID
    AND dbo.Frost.theMonth = cte.Mo
ORDER BY dbo.ternean.theMonth

1 个答案:

答案 0 :(得分:2)

我试图复制你的错误但不能。

为什么使用多部分标识符作为字段名称? select语句中的字段列表只能引用from子句中的表,首先读取此查询似乎是直接在dbo模式中引用表。

给你的表一些很好的简单别名,即

FROM dbo.Frost AS F

并像这样使用它们

F.RTNum

其次,您可以简化您的案例陈述,只进行一次测试,即:

CASE WHEN SUBSTRING(T.ACH_AcctNo, 2, 20) <> F.AccountNumber
    THEN 'DO not match'
    ELSE 'match'
END AS [Account # match]