1

I'm trying to delete a user and all the related records tied to him, and I have no clue how to use the SQL INNER JOIN statement, is there any way to do something in the style of:

DELETE * FROM tblUsers, tblEnrollment, tblLinkActivities, tblFullSchedule, tblSchedule, tblLinkMedical
WHERE [IDUser] = ?

(I know that's completely incorrect)

My relationships chart looks like so:

Relationships

Would it be easier to use 6 delete commands? Or is there another command that does that? Thanks a bunch..

Taabkl
  • 103
  • 1
  • 9
  • 1
    Another - and quite common - approach is to have a boolean field `Inactive` in the user table. To "delete" a user, set this field to True. Then, for all normal usage, use a query, ActiveUsers, like: `Select * From tblUsers Where Inactive = False`. – Gustav Apr 04 '19 at 14:34

2 Answers2

2

Since you already have defined relationships with referential integrity, simply set the Cascade Delete Related Records option for each relationship.

See https://support.office.com/en-us/article/create-edit-or-delete-a-relationship-dfa453a7-0b6d-4c34-a128-fdebc7e686af#__bmcascade

This way you only need to delete from tblUsers, all related records are deleted automatically.

If you can't or don't want to do this, you need to run separate delete queries on the related tables before deleting the main record.

Andre
  • 26,751
  • 7
  • 36
  • 80
1

There's no way to delete records in multiple tables at the same time in single sql query. You need to write multiple delete statements. The better way is to write an inner query with all tables involved and delete in each table. For ex: delete from dept where DEPTNO IN (Select a.DEPTNO from emp a , dept b where a.DEPTNO=b.DEPTNO and a.DEPTNO=10) delete from emp where DEPTNO IN (Select a.DEPTNO from emp a , dept b where a.DEPTNO=b.DEPTNO

sudheer
  • 33
  • 8