Sql server - recursive delete

后端 未结 5 2077
别跟我提以往
别跟我提以往 2020-12-28 19:59

I\'m trying to delete user\'s data and all it\'s related data that is located in different tables. All the tables have Foreign Keys but without cascade delete.

I in

5条回答
  •  -上瘾入骨i
    2020-12-28 20:26

    Those are the best and most efficient ones. For production queries I would use 2.

    The only other ways I can think of would (IMO) only be suitable for quick and dirty removal of data in a test environment (avoiding the need to analyse the correct order)

    1. Disable all FKs delete the desired data then re-enable the FKs. This is inefficient as they need to be re-enabled WITH CHECK to avoid leaving the FKs in an untrusted state which means that all preserved data needs to be re-validated.
    2. List out all DELETE statements on affected tables in arbitrary order and run the batch as many times as necessary until it succeeds with no FK errors.

提交回复
热议问题