开发者

MySql stored procedures, delete record logically or phisically depending on existing table references

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 physically 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 add开发者_StackOverflow中文版resses INNER JOIN tempids ON addresses.id = tempids.id;
ELSE
    UPDATE addresses SET deleted=TRUE INNER JOIN tempids ON addresses.id = tempids.id;

How do I accomplish this?

Thanks.


You can check ROW_COUNT() function value after deleting.

http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_row-count

So "no records deleted" condition is replaced with ROW_COUNT() == 0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜