在游标内使用 Merge 语句
我们需要填充一个主表,该表由 20 个不同表中的列组成。
我编写了一个存储过程来连接一些返回最大列数的表并将它们放在游标中。
现在。我正在使用 for 循环来迭代游标记录,以便可以将它们插入主表中。
如何在游标 for 循环内使用合并语句,以便我可以检查是否需要更新现有行或插入新行,具体取决于记录是否已存在。
如果我们可以在游标 for 循环中使用 merge 语句,有什么想法吗?有什么例子吗?
We have a requirement to populate a master table which consists of columns from a set of 20 different tables.
I have written a stored procedure to join some of the tables that return me max number of columns and have them in a cursor.
Now. I am using for loop to iterate through the cursor records so I can insert them into the master table.
How I can use a merge statement inside the cursor for loop so I can check if I need to update existing row or insert a new row depending if the records already exists or not.
Any ideas if we can use merge statement inside a cursor for loop? Any examples?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过从
DUAL
中选择光标的数据来执行MERGE
。例如,使用一些数据创建源表和目标表
运行合并
并验证合并是否符合我们的要求。第 1 行已更新,第 2 行已插入。
然而,以这种方式构建代码通常没有太大意义。通常,最好将用于打开游标的查询直接放入 MERGE 语句中,这样您就可以选择所有数据,而不是从
DUAL
中选择一行数据您想要合并您尝试合并数据的所有表。当然,为该查询创建一个 MERGE 语句可以查询的视图以保持 MERGE 语句的可读性可能是有意义的。You can do a
MERGE
by selecting the cursor's data fromDUAL
. For exampleCreate a source and destination table with some data
Run the merge
And verify that the merge did what we wanted. Row 1 was updated and row 2 was inserted.
However, it generally wouldn't make too much sense to structure the code this way. You'd generally be better off putting the query that you'd use to open the cursor into the MERGE statement directly so that rather than selecting one row of data from
DUAL
, you're selecting all the data you want to merge from all the tables you're trying to merge the data from. Of course, it may make sense to create a view for this query that theMERGE
statement can query in order to keep theMERGE
statement readable.