简体   繁体   English

使用 CTE 时出现无效的列名错误?

[英]Getting Invalid column name error when using a CTE?

I have this query to update a column in a staging table.我有这个查询来更新临时表中的列。

WITH CTE AS
(
    SELECT
        [dbo].[udf_Text](A.column1) AS [NewColumn1], 
        column1 AS [OldDesc],
        ID_1, ID_2
    FROM
        [staging].[Table] A
) 
UPDATE [staging].[Table]
SET [staging].[Table].column1 = CTE.[NewColumn1]
WHERE [staging].[Table].ID_1 = CTE.ID_1 AND ID_2 = CTE.ID_2

What I'm trying to do is to pull the old column in the CTE and then update it with the new column that has the UDF applied to it.我要做的是在 CTE 中提取旧列,然后使用应用了 UDF 的新列对其进行更新。 so I wrote this query and I'm getting this error.所以我写了这个查询,我收到了这个错误。

Msg 207, Level 16, State 1, Line 45消息 207,第 16 层,State 1,第 45 行
Invalid column name 'NewColumn1'列名“NewColumn1”无效

How can I achieve this or maybe if there's a better way around this?我怎样才能做到这一点,或者如果有更好的方法来解决这个问题?

You need to actually reference the CTE in your UPDATE statement:您需要在UPDATE语句中实际引用CTE:

WITH CTE AS
(
    ....
) 
UPDATE t
SET column1 = CTE.[NewColumn1]
FROM [staging].[Table] t
INNER JOIN CTE ON t.ID_1 = CTE.ID_1 AND t.ID_2 = CTE.ID_2

Although, as mentioned by others, you need to join the CTE to be able to reference it, in this particular example you can actually update the CTE directly .尽管正如其他人所提到的,您需要加入 CTE 才能引用它,但在这个特定示例中,您实际上可以直接更新 CTE

This assumes that ID_1 and ID_2 uniquely identify a row这假设ID_1ID_2唯一标识一行

WITH CTE AS
(
    SELECT
        [dbo].[udf_Text](A.column1) AS [NewColumn1], 
        column1 AS [OldDesc],
        ID_1, ID_2
    FROM
        [staging].[Table] A
) 
UPDATE CTE
SET column1 = CTE_AR.[NewColumn1]

The CTE needs to follow rules for updatable views CTE 需要遵循可更新视图的规则

Why not just write the logic directly?为什么不直接写逻辑呢?

UPDATE [staging].[Table]
    SET [staging].[Table].column1 = [dbo].[udf_Text](A.column1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM