使用连接更新 - 多数据库/表
我有一种情况,我想仅使用一个指令更新多个表中的多个字段。我需要一个语法来在多个数据库(Oracle 和 MSSQL)上执行此类操作。
目前,我陷入了 MSSQL 的以下语句:
update table1
set table1.value = 'foo'
from table1 t1 join table2 t2 on t1.id = t2.tab1_id
where t1.id = 1234
我想在同一语句中更新 t2 中的字段。
此外,我想在 Oracle 上执行相同的更新。
编辑:
似乎我无法在一个语句中更新多个表。
使用 Join 更新时是否有适用于 Oracle 和 MSSql 的语法?
问候
I have a scenario where I would like to update multiple fields in multiple Tables using just one instuction. I need a Syntax to perform such opperations on multiple Databases (Oracle and MSSQL).
At the moment I am stuck at the following statement from MSSQL:
update table1
set table1.value = 'foo'
from table1 t1 join table2 t2 on t1.id = t2.tab1_id
where t1.id = 1234
I would like to update a field in t2 aswell in the same statement.
Further I would like to perform the same Update(s) on Oracle.
EDIT:
Seems like I can not update multiple Tables in just one statement.
Is there a syntax that works for Oracle and MSSql when updating using a Join?
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设当您重新提出问题时,您希望语法能够同时适用于 Oracle 和 SQL Server,即使它不可避免地只会影响一张表。
两个平台都支持入门级 SQL-92 标准代码,因此以下“标量子查询”SQL-92 代码应该可以工作:
请注意,在使用
Ttble1
t1 时> 是根据 SQL-92 标准的有效语法,这将具体化一个表,然后UPDATE
将以具体化表“t1”为目标,并使基表“table1”不受影响,我认为这不受影响想要的效果。虽然我相当确定 Oracle 和 SQL Server 在这方面都是不合规的,并且在实践中会按预期工作,但通过完全限定目标表来极度谨慎并坚持 SQL-92 语法并没有什么坏处。人们往往不喜欢上述子查询中的“重复”代码(即使优化器应该足够聪明,只对其进行一次评估)。
Oracle 和 SQL Server 的最新版本都支持标准 SQL:2003
MERGE
语法,也许能够使用与此接近的东西:我刚刚注意到你的示例比我最初想象的还要简单,只是需要一个应该在大多数 SQL 产品上运行的简单子查询,例如
I assume when you re-posed the question you want syntax that will work on both Oracle and SQL Server even though it will inevitably affect only one table.
Entry level SQL-92 Standard code is supported by both platforms, therefore the following 'scalar subqueries' SQL-92 code should work:
Note that while using the correlation name
t1
forTtble1
is valid syntax according to the SQL-92 Standard this will materialize a table and theUPDATE
will then target the materialized table 't1' and leave your base table 'table1` unaffected, which I assume is not the desired affect. While I'm fairly sure both Oracle and SQL Server are non-compliant is this regard and that in practise would work as expected, there's no harm in being ultra cautious and sticking to the SQL-92 syntax by fully qualifying the target table.Folk tend not to like the 'repeated' code in the above subqueries (even though the optimizer should be smart enough to evaluate it only once).
More recent versions of Oracle and SQL Server support both support Standard SQL:2003
MERGE
syntax, would may be able to use something close to this:I just noticed your example is even simpler than I first thought and merely requires a simple subquery that should run on most SQL products e.g.
在 Oracle 上,您只能更新一张表,但您可以考虑使用触发器。
on Oracle, you can update only one table , but you could think of using a trigger .