使用CTE更新 - 语法错误?

时间:2012-07-30 01:52:20

标签: sql sql-server-2008 tsql common-table-expression

我正在尝试使用CTE中包含的数据更新表。不幸的是我收到语法错误,我不太清楚为什么。目前的代码是:

declare @period_id  integer =
                (
                     select period_id
                     from   property.period
                     where  getdate() between period_start and period_end
                 )

;with cte_reclassified as
(
    select  building_id ,
            lease_id ,
            scca_broad_category_code ,
            scca_fine_categories_code ,
            scca_notes_code ,
            scca_sales_group_code ,
            scca_uplift
    from    property.lease_period
    where   period_id = @period_id
)

update  property.lease_period lp
from    cte_reclassified r
set     lp.scca_broad_category_code = r.scca_broad_category_code
where   lp.lease_id = r.lease_id
        and lp.building_id = r.building_id

我收到的语法错误是:

  

Msg 102,Level 15,State 1,Line 21'lp'附近的语法不正确。

有没有办法做我想在这里尝试的事情?我已经尝试使用谷歌搜索主题但是达到了死胡同 - 任何建议都会受到赞赏!

2 个答案:

答案 0 :(得分:2)

我认为您希望从语句的property部分中取出“UPDATE”(因为您通过CTE进行更新)并将SET子句放在FROM之前{1}}:

update  lease_period lp
set     lp.scca_broad_category_code = r.scca_broad_category_code
from    cte_reclassified r
where lp.lease_id = r.lease_id

答案 1 :(得分:1)

您无需在更新语句上创建别名

语法:Update [TableName] SET [ColumnName]='New Value' WHERE ColumnName='Filter'

看看这篇关于@Robin Day如何完成的SO帖子:

SQL Server UPDATE from SELECT

最好的问候

相关问题