【问题标题】:Why the scope of with clause is not extended to the where clause of the update statement?为什么 with 子句的范围没有扩展到 update 语句的 where 子句?
【发布时间】:2019-11-07 16:22:12
【问题描述】:

我收到错误消息“无法绑定多部分标识符“T.stdID”。”用于以下 t-sql 查询。

如果 update 被 select...from... 替换,其中 T.stdID = ...,则 T.stdID 为 有界没有任何问题;但是,它不限于更新的部分!

with T as
(select ID as stdID, sum(credits) as crd
from takes, course
where takes.course_id = course.course_id
group by ID)
update student
set 
    tot_cred = T.crd
where
    student.ID = T.stdID

消息 4104,第 16 级,状态 1,第 125 行 无法绑定多部分标识符“T.stdID”。

完成时间:2019-11-06T19:37:49.3354478+02:00

【问题讨论】:

标签: sql-server tsql sql-update


【解决方案1】:
with T as
(select ID as stdID, sum(credits) as crd
from takes, course
where takes.course_id = course.course_id
group by ID)
update student
set 
    tot_cred = T.crd

from
    student, T

where
    student.ID = T.stdID

非常感谢@Sean Lange!

【讨论】:

  • 自 ANSI-92 标准以来,以您的方式处理连接一直不是公认的方法。
  • 感谢您提及这一点。我阅读了@Sean Lange 放置的链接,我明白为什么不推荐使用这种方式。但是,我的主要问题是为什么 T.stdID 在更新的部分没有被识别。
  • 我明白这不是您问题的重点,但请记住您的答案适用于所有人。理想情况下,您的答案应该是下一个面临相同问题的人的良好实践模型。
  • 感谢@BarneyL 的敏感!
猜你喜欢
  • 2019-07-15
  • 2011-08-07
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
相关资源
最近更新 更多