使用绑定的多部分标识符更新 SQL 中的多个列
我正在尝试使用子查询更新 MS SQL 语句中的多个列。搜索使我得到类似的结果:
UPDATE table1
SET col1 = a.col1, col2 = a.col2, col3 = a.col3 FROM
(SELECT col1, col2, col3 from table2 where <expression>) AS a
WHERE table1.col1 <expression>
我的问题是,在内部 WHERE
表达式中,我需要引用 table1 中的特定字段:
UPDATE table1
SET col1 = a.col1, col2 = a.col2, col3 = a.col3 FROM
(SELECT col1, col2, col3 from table2 where table1.col0 = table2.col0) AS a
WHERE table1.col1 <expression>
当我运行该查询时,我得到“无法绑定多部分标识符“table1.col0”。 ”。显然,当使用该语法时,SQL 无法绑定子查询中的当前 table1 记录。现在,我正在对每个字段重复子查询并使用语法:
UPDATE table1
SET col1 = (subquery), col2 = (subquery)...
但是每列执行一次子查询(这是非常昂贵的),我 想避免吗?
有什么想法
I'm trying to update multiple columns in a MS SQL statement using a sub-query. A search led me to something like:
UPDATE table1
SET col1 = a.col1, col2 = a.col2, col3 = a.col3 FROM
(SELECT col1, col2, col3 from table2 where <expression>) AS a
WHERE table1.col1 <expression>
My problem is that in the inner WHERE
expression I need a reference to a specific field in table1:
UPDATE table1
SET col1 = a.col1, col2 = a.col2, col3 = a.col3 FROM
(SELECT col1, col2, col3 from table2 where table1.col0 = table2.col0) AS a
WHERE table1.col1 <expression>
When I run that query I get "The multi-part identifier "table1.col0" could not be bound.
". Apparently when using that syntax SQL cannot bind the current table1 record in the subquery. Right now I am repeating the subquery for each field and using the syntax:
UPDATE table1
SET col1 = (subquery), col2 = (subquery)...
But that executes the subquery (which is very expensive) once per column, which I would like to avoid.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 sql server 中,您可以在更新查询中使用
from
子句。像在选择中一样连接表。您正在更新的表必须包含在联接中。in sql server, you can use a
from
clause in an update query. Join the tables as you would in a select. The table you are updating must be included in the joins.或者,如果您不喜欢连接语法,这也可以:
Or if you dislike the join syntax this will also work:
您的汽车使用 CROSS APPLY 命令从子选择中更新多个列
Your car use CROSS APPLY command to update multiple columns from sub select