1

Table1.

id | name
 1 | Test

Table2.

id | post | table1_id
 1 | mypst| 1

I need to remove a row from Table1 where id=1 and all rows from Table2 where table1_id=(1 is id from Table1).

I'm trying this:

DELETE FROM Table1 
INNER JOIN Table2 ON Table2.table1_id = Table1.id AND Table1.id = 1

but I'm getting error:

Incorrect syntax near the keyword 'INNER'.

What's wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marius
  • 161
  • 1
  • 4
  • 10

2 Answers2

2

You shouldn't be doing deletes from multiple tables in one query

DELETE FROM Table2 WHERE table1_id = 1;
DELETE FROM Table1 WHERE id = 1

should be fine. Is there any specific reason you wish to do it using JOIN?

Vivek
  • 382
  • 4
  • 12
  • no, just interesting for my skills, thank you pretty much! I think this is even better solution. – Marius Jan 16 '13 at 15:04
  • 1
    @Marius - Not only shouldn't but can't. SQL Server doesn't have any syntax to delete from more than one table (though you can set up foreign keys with cascading deletes) – Martin Smith Jan 16 '13 at 15:14
2

Lets assume you are doing things right and made a foreign key (Table2.table1_id = Table1.id). Then all you need is to set ON DELETE CASCADE on Table1.

In this case everything you should do is:

DELETE FROM Table1 WHERE id = 1

...and relax. This is data consistency, dude :)

Andrey Voloshin
  • 345
  • 1
  • 11