在一个 SQL 查询中插入临时表并更新另一个表 (Oracle)
这是我想要做的:
1) 将原始表中的一些值插入到临时表中
INSERT INTO temp_table SELECT id FROM original WHERE status='t'
2) 更新原始表
UPDATE original SET valid='t' WHERE status='t'
3) 基于两个表之间的联接进行选择
SELECT * FROM original WHERE temp_table.id = original.id
有没有办法结合步骤 1 和 2?
Here's what I'm trying to do:
1) Insert into a temp table some values from an original table
INSERT INTO temp_table SELECT id FROM original WHERE status='t'
2) Update the original table
UPDATE original SET valid='t' WHERE status='t'
3) Select based on a join between the two tables
SELECT * FROM original WHERE temp_table.id = original.id
Is there a way to combine steps 1 and 2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以通过在 PL/SQL 中执行更新并使用 RETURNING 子句将更新的 id 获取到 PL/SQL 表中来组合这些步骤。
编辑:
如果您仍然需要进行最终查询,您仍然可以使用此方法插入到 temp_table 中;尽管取决于最后一个查询的目的,但可能还有其他方法可以实现您想要的目的。举例说明:
You can combine the steps by doing the update in PL/SQL and using the RETURNING clause to get the updated ids into a PL/SQL table.
EDIT:
If you still need to do the final query, you can still use this method to insert into the temp_table; although depending on what that last query is for, there may be other ways of achieving what you want. To illustrate:
不可以,DML 语句不能混合。
有一个 MERGE 语句,但它仅适用于单个表的操作。
No, DML statements can not be mixed.
There's a MERGE statement, but it's only for operations on a single table.
也许创建一个 TRIGGER ,在插入后触发temp_table 并更新原始表
Maybe create a TRIGGER wich fires after inserting into a temp_table and updates the original
创建一个游标来保存插入中的值,然后循环更新表。首先不需要创建临时表。
Create a cursor holding the values from insert and then loop through the cursor updating the table. No need to create temp table in the first place.
您可以使用 MERGE 语句和 DML 错误日志记录来组合步骤 1 和 2。选择两倍数量的行,更新其中一半,并强制另一半失败,然后将其插入到可用作临时表的错误日志中。
下面的解决方案假设您对 ID 有主键约束,但还有其他方法可以强制失败。
虽然我认为这很酷,但我建议您不要使用它。它看起来很奇怪,有一些奇怪的问题(对 TEMP_TABLE 的插入是自动提交的),并且可能非常慢。
You can combine steps 1 and 2 using a MERGE statement and DML error logging. Select twice as many rows, update half of them, and force the other half to fail and then be inserted into an error log that you can use as your temporary table.
The solution below assumes that you have a primary key constraint on ID, but there are other ways you could force a failure.
Although I think this is pretty cool, I would recommend you not use it. It looks very weird, has some strange issues (the inserts into TEMP_TABLE are auto-committed), and is probably very slow.