Sql Cleanup script, delete from one table that's not in the other

半腔热情 提交于 2020-01-17 14:05:11

问题


We wrote a cleanup script in SQL(DB2) as400 to do cleanup of tables. ps we are fixing the processes that is causing the data issues.

The SQL : DELETE FROM p6prodpf A WHERE (0 = (SELECT COUNT(*) FROM P6OPIPF B WHERE B.OPIID = A.OPIID))

Its simple code to check if theres a record in p6prodpf that has no record in P6OPIPF then delete the record in p6prodpf.

My problem that I am facing is that there's instances where the p6prodpf is being deleted even if theres a record in P6OPIPF.

Is there a better way of doing this or safer way.. Is there any reason why this could be happening.

The script runs 3am in the morning.

It also feels like a sequencing issue but when I check the record in P6OPIPF it exists but its deleted in p6prodpf.


回答1:


Use "NOT EXISTS" instead of "0 =":

DELETE FROM p6prodpf A WHERE NOT EXISTS (SELECT 1 FROM P6OPIPF B WHERE B.OPIID = A.OPIID)


来源:https://stackoverflow.com/questions/31676517/sql-cleanup-script-delete-from-one-table-thats-not-in-the-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!