Sql 如何编写此CTE查询?

Sql 如何编写此CTE查询?,sql,sql-server,sql-server-2008,rdbms,common-table-expression,Sql,Sql Server,Sql Server 2008,Rdbms,Common Table Expression,您好,我想根据其他表中的值更新1个表。我可以使用Join来编写update语句,事实上我已经编写了它,它可以使用Join来工作。但出于好奇,我想用CTE。我编写了以下查询,但它似乎不起作用。有人能告诉我问题出在哪里吗?CTE是否强制要求在末尾使用Select语句?为什么我不能写Update语句 WITH cte(uid, col1) As ( Select uid, col1 From [User] ) Update t2 Set col1 = cte.col1

您好,我想根据其他表中的值更新1个表。我可以使用Join来编写update语句,事实上我已经编写了它,它可以使用Join来工作。但出于好奇,我想用CTE。我编写了以下查询,但它似乎不起作用。有人能告诉我问题出在哪里吗?CTE是否强制要求在末尾使用Select语句?为什么我不能写Update语句

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

你仍然需要加入你的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]
编辑我想通过使用SQL WHERE JOIN可以避免使用“JOIN”关键字,但这并不是一个好的做法

...        
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

你仍然需要加入你的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]
编辑我想通过使用SQL WHERE JOIN可以避免使用“JOIN”关键字,但这并不是一个好的做法

...        
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

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