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?
You can do a
MERGEby 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 theMERGEstatement can query in order to keep theMERGEstatement readable.