1

你好,我想根据其他表中存在的值更新1个表。我可以使用Join来写更新语句,并且事实上我写了它,它使用Join来工作。但出于好奇,我想使用CTE。我写了下面的查询,但它似乎不工作。有人可以告诉我这是什么问题吗? CTE是否强制要求Select语句?为什么我不能写更新语句?如何编写此CTE查询?

WITH cte(uid, col1) 
As 
(
    Select uid, col1 
     From [User] 
) 
Update t2 
    Set col1 = cte.col1 
     Where uid = cte.uid 

回答

1

您仍然需要加入回你的CTE,像这样

WITH cte([uid], col1) 
As 
(
    Select [uid], col1 
     From [User] 
) 
Update t2 
    Set col1 = cte.col1 
    FROM t2 inner join cte cte 
    on t2.[uid] = cte.[uid] 

编辑我想你可以通过使用old-style SQL WHERE加入避免“加入”的关键字,但是这ISN”真的很好的做法。

...   
FROM t2, cte cte 
WHERE t2.[uid] = cte.[uid] 

另外请注意,您也可以通过CTE更新,如视图,只要您只更新一个表。

WITH cte(userCol1, t2Col1) 
As 
(
    Select [u].col1 as userCol1, t2.col1 as t2Col1 
     From [User] u 
     inner join t2 
     ON u.[uid] = t2.[uid] 
) 
Update cte 
    Set t2Col1 = userCol1 
+0

噢,如果是这样的话,我可以忽略CTE并用JOIN写一个简单的更新。 –