My situation looks like this:
Table STOCK_ARTICLES:
ID *[PK]*OTHER_DB_IDITEM_NAME
Table LOCATION:
ID *[PK]*LOCATION_NAME
Table WORK_PLACE:
ID *[PK]*WORKPLACE_NAME
Table INVENTORY_ITEMS:
ID *[PK]*ITEM_NAMESTOCK_ARTICLE *[FK]*LOCATION *[FK]*WORK_PLACE *[FK]*
The 3 FKs in INVENTORY_ITEMS reference the "ID" columns in the respective other tables, obviously.
The relevant tables here are STOCK_ARTICLE and INVENTORY_ITEMS.
Now there is a SQL job consisting of several steps (SQL scripts) that "synchronizes" the database mentioned above with another database (OTHER_DB). One of the steps inside this job is for "cleanup". It deletes all records from STOCK_ITEMS where there's no corresponding record in the other database with the same ID.It looks like this:
DELETE FROM STOCK_ARTICLES WHERE NOT EXISTS (SELECT OTHER_DB_ID FROM [OTHER_DB].[dbo].[OtherTable] AS other WHERE other.ObjectID = STOCK_ARTICLES.OTHER_DB_ID)
But this step always fails with:
The DELETE statement conflicted with the REFERENCE constraint"FK_INVENTORY_ITEMS_STOCK_ARTICLES". The conflict occurred in database"FIRST_DB", table "dbo.INVENTORY_ITEMS", column 'STOCK_ARTICLES'. [SQLSTATE 23000] (Error 547) The statement has been terminated. [SQLSTATE 01000] (Error 3621). The step failed.
So the problem is that it can't delete records from STOCK_ARTICLES when they are referenced by INVENTORY_ITEMS.But this cleanup needs to work.Which means that I probably have to extend the cleanup script so that it first identifies the records that should be deleted from STOCK_ITEMS, but can't because the corresponding ID is referenced from inside INVENTORY_ITEMS.Then it should first delete those records inside INVENTORY_ITEMS, and after that delete the records inside STOCK_ARTICLES.Am I right?How would the SQL code look like then?
Thank you.