【问题标题】:Update using CTE - Syntax error?使用 CTE 更新 - 语法错误?
【发布时间】:2012-07-30 01:52:20
【问题描述】:

我正在尝试使用 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

我收到的语法错误是:

消息 102,级别 15,状态 1,第 21 行 'lp' 附近的语法不正确。

有没有办法做我在这里尝试的事情?我试过用谷歌搜索这个主题,但遇到了死胡同 - 任何建议都将不胜感激!

【问题讨论】:

  • 您确定您完全按照原样粘贴了吗?我想知道这是因为字母“lp”没有出现在代码中的任何地方
  • @AdamBatkin 哎呀!为 s/oflow 削减它的副产品。现在更新。编辑:固定!
  • 我认为 SQL Server 不允许您在更新语句中指定别名。只需删除别名并将出现的地方替换为表名即可。

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


【解决方案1】:

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

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

【讨论】:

  • 正如@GordonLinoff 提到的,您可能需要将别名lp 从声明中删除
  • 太好了,明白了。谢谢!
【解决方案2】:

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

关于它的语法:Update [TableName] SET [ColumnName]='New Value' WHERE ColumnName='Filter'

查看这篇 SO 帖子,了解 @Robin Day 是如何完成的:

SQL Server UPDATE from SELECT

最好的问候

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2016-04-17
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多