Refer to my previous posting.
Sql Cleanup script, delete from one table that's not in the other1
Using DB2 for IBM i (As400, Db2).
I am executing the following sql as a cleanup script 3am.
DELETE FROM p6prodpf A WHERE (0 = (SELECT COUNT(*) FROM P6OPIPF B WHERE B.OPIID = A.OPIID))
I have a different process that at the same time that this sql runs inserts two records, the first record is the P6OPIPF record and then inserts the detail record into P6PRODPF.
The problem.
The P6PRODPF record is missing after the SQL cleanup ran. But remember that the process that stores the records ran the same time.
How I understand the SQL is that it go's through P6PRODPF and checks if the record is in P6OPIPF if its not in P6OPIPF then delete P6PRODPF.
But then I ran Visual Explain in I systems navigator on this SQL and got the following result.
Now I am confused.
After Visual explain It looks like the statement starts with checking P6OPIPF.
So then it reads: If there's a record in that instance of time in P6OPIPF and no record with the same key in P6PRODPF then delete the P6PRODPF.
This could explain my problem that P6PRODPF gets deleted when my process that inserts the records and the sql script runs at the same time.
So how I see it in Sequence.(My theory)
The process that inserts the two records starts.
The process that inserts the two records inserts the first record in
P6OPIPF.- At the same time the SQL cleanup runs. the query see's the
P6OPIPFrecord and checks if it has aP6PRODPFrecord. At this stage there is still noP6PRODPFinserted so Sql thinks it needs to delete the record inP6PRODPF. - In the same time The process that inserts the two records inserts the
second record in
P6PRODPF. - And because the Sql did not see the
P6PRODPFat that stage it deletes the new inserted record inP6PRODPFleaving aP6OPIPFrecord with noP6PRODPFrecord.
Am I correct?
What I actually want to know is just the Delete script listed above. How I understand the SQL is that it go's through P6PRODPF and checks if the record is in P6OPIPF if its not in P6OPIPF then delete P6PRODPF. But after the visual explain I can see its starts with checking P6OPIPF. So What will the delete statement first check?
The code of the insert is generated in CA PLEX generator. RPGIV code.
My one function that will insert first P6OPIPF(OperationsItem.Update.InsertRow) and then its detail in P6PRODPF(ProductDetail.Update.InsertRow).
My Scheduled function code that will execute the delete Script.
Scheduled delete script function
Hope it makes sense.




DELETE FROM P6ProdPF A WHERE NOT EXISTS (SELECT 1 FROM P6OpiPF B WHERE A.opId = B.opId). In many-to-one situations this is likely to be faster (instead of needing to count the rows, it just checks for any).