使用 CTE 使用来自另一个 table 的行更新 table

UPDATE a table with rows from another table using a CTE

我需要用 A_solarTypeDB.dbo.spaceList

中同一列的值更新 B_solarTypeDB.dbo.spaceList 中所有行的列

我的 CTE 低于 returns A_solarTypeDB.dbo.spaceList 中不在 B_solarTypeDB.dbo.spaceList

中的所有 astroID 值

有没有办法用这些值对 B_solarTypeDB.dbo.spaceList 进行更新?

这是我对 CTE 的尝试:

UPDATE B_solarTypeDB.dbo.spaceList
SET astroID = 
;WITH CTE AS
(
    SELECT astroID FROM A_solarTypeDB.dbo.spaceList
    EXCEPT
    SELECT astroID FROM B_solarTypeDB.dbo.spaceList
)
SELECT astroID 
FROM A_solarTypeDB.dbo.spaceList
WHERE astroID IN (SELECT astroID FROM CTE)

但是我在“;”附近遇到语法错误

这是来自 A_solarTypeDB.dbo.spaceList 的示例数据:

spaceID     spaceName    typeID     astroID
2937        Mars         1          9481ffg1
2938        Titan        3          4728ffu3
2939        MG1          7          4937fft5

我需要在 B_solarTypeDB.dbo.spaceList 上进行更新,因为有时 astroID 的值为 NULL,而它应该与 A_solarTypeDB 数据库中的值相同。

谢谢!

你可以在没有 CTE 的情况下做到这一点:

    UPDATE typeBdb.dbo.spaceList
    SET astroID = T2.astroID
    FROM
    (
       SELECT astroID,CommonUniqueID
       FROM typeAdb.dbo.spaceList
       WHERE astroID IN 
       (
            SELECT astroID 
            FROM (
                        
                    SELECT astroID FROM typeAdb.dbo.spaceList
                    EXCEPT
                    SELECT astroID FROM typeBdb.dbo.spaceList
                    
               ) T1
    
       )
    ) T2
   WHERE typeBdb.dbo.spaceList.CommonUniqueID = T2.CommonUniqueID