我更新了临时表,并更新了原始表SQL Server

时间:2013-12-13 10:12:11

标签: sql-server

我运行此查询以更新临时表CTE_Companies,并更新了原始Companies表。我现在该怎么办:(

with CTE_Companies
(ZIP)
As
(
Select ZIP from Companies
)

Update  CTE_Companies 
set CTE_Companies.ZIP= '0'+CTE_Companies.ZIP
where len(CTE_Companies.ZIP) = 4 

3 个答案:

答案 0 :(得分:3)

common-table-expression不是临时表。它更像是一个或多个表上的子查询。如果您从单个表中选择,那么您将更新此表。

这是设计上非常有用的,因为您可以轻松更改Update / DeleteSelect来查看您要更改或删除的内容。因此,您应在Where中添加CTE条件。

答案 1 :(得分:0)

如果没有基表,则无法更新表表达式。 使用临时表。

答案 2 :(得分:0)

BEGIN TRAN

WITH CTE_Companies
(ZIP)
As
(
Select ZIP from Companies
)

Update  CTE_Companies 
set CTE_Companies.ZIP= SUBSTRING (1, CTE_Companies.ZIP, LEN(CTE_Companies.ZIP) - 1)
where
    len(CTE_Companies.ZIP) = 5 
    and CTE_Companies.ZIP LIKE '0%'


-- check if your data is ok and then change the next line to COMMIT TRAN     
ROLLBACK TRAN