views:

22

answers:

0

Hi,

I have to write a Stored Procedure to delete record from a table.

I have a memory table "tableids" where I store all the ids to delete from another table, say "addresses".

CREATE TABLE `tempids` (
    `id` INT(11) NULL DEFAULT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=MEMORY
ROW_FORMAT=DEFAULT

I could do this:

DELETE FROM addresses INNER JOIN tempids ON addresses.id = tempids.id;

BUT I want to phisically delete the records in the addresses table if they have no references in other known tables in my model; otherwise I want to delete the records logically. I'd like to do this in a single shot, that is without writing a loop in my SP.

In pseudo-sql code:

DELETE 
    FROM addresses 
WHERE
    id NOT IN (SELECT address_id FROM othertable1 WHERE address_id=(SELECT id FROM tempids))
AND     id NOT IN (SELECT address_id FROM othertable2 WHERE address_id=(SELECT id FROM tempids))
...more possible references in other tables

IF "no records deleted"
    DELETE FROM addresses INNER JOIN tempids ON addresses.id = tempids.id;
ELSE
    UPDATE addresses SET deleted=TRUE INNER JOIN tempids ON addresses.id = tempids.id;

How to accompish this?

Thanks.