无效的对象名称'来源'使用合并时

时间:2015-10-30 20:41:25

标签: sql sql-server tsql

我在合并声明中使用它,但现在我收到错误无效的对象名称'来源'。

我没有在我的任何其他合并声明中收到此错误。来源如下。我已在某种程度上匿名,所以如果不清楚,请告诉我

 MERGE dbo.Destination WITH (HOLDLOCK) AS Target
USING
(
SELECT DISTINCT id, col3,   
 CAST(LEFT(DATEADD(m,months,CONVERT(date,CONCAT(origination,'/01'))),7) as   varchar(20))  as CalendarMonth,
 col1, col2,col4 FROM dbo.Staging
) AS Source
ON (Target.ID=Source.id
AND Target.Month=Source.col3)
    WHEN MATCHED THEN
        UPDATE SET
        Target.CalendarMonth=Source.CalendarMonth,
        Target.colF= (SELECT CASE WHEN col1>0 THEN 1 END AS colF FROM Source),
        Target.colD=(SELECT CASE WHEN col4>0 THEN 1 END AS colD
                                    FROM Source),
        Target.colC=(SELECT CASE WHEN col1=0 AND col2=0
                                    THEN 1 END AS colC FROM Source),
        Target.colB(SELECT CASE WHEN col1>0 AND col2
                                    THEN 1 END AS colB FROM Source),
        Target.colG=(SELECT CASE WHEN col1>0 THEN col1 END AS colG FROM Source),
        Target.colE=(SELECT CASE WHEN col4>0 THEN col3 END
                                    AS colE FROM Source),
        Target.PaidMonth=(SELECT CASE WHEN col1=0 AND col2=0
                                    THEN col3 END AS PaidMonth 
                                    FROM Source),
        WHEN NOT MATCHED BY TARGET THEN
        INSERT
        (Destination Table columns
        )
        VALUES
        (   Source values including derived values from above);

END

提前感谢您的帮助!

更新

@Sam cd的建议帮助了我用派对列替换了派对列中的select语句,其中col4> 0 THEN col3 END等等。谢谢大家的帮助!

2 个答案:

答案 0 :(得分:1)

您的问题可能在于如何表达更新。使用子查询取消别名。即这里SQL会查找数据库中实际命名为source的表,这可能不存在。

@

你不需要这样说,因为Target.colF= (SELECT CASE WHEN col1>0 THEN 1 END AS colF FROM Source), 已经别名,你可以说

Source

答案 1 :(得分:0)

你的问题在这里:

VALUES
    (   Source values including derived values from above)

这是否意味着评论?