简体   繁体   中英

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. so I wrote this query and I'm getting this error.

Msg 207, Level 16, State 1, Line 45
Invalid column name '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:

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 .

This assumes that ID_1 and ID_2 uniquely identify a row

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

Why not just write the logic directly?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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