tags:

views:

70

answers:

2

I want to delete all the records where field name class="10010" from Table A and AentryId = BentryId from Table B.

if i delete the entryId 12 which matches className=10010 from Table A and the same time that same id should delete from Table B also.

Table A:

AentryId  className     
12      10010
13      10011
14      10010
15      10011

Table B:

BentryId  name   
12         xyz
13         abc
14         aaa
+1  A: 

Following may be final query you are looking for

delete form TableA where   class="10010" and AentryId in ( select BentryId from tableB)

Cascade delete is one of the option that allow you to delete data from child and form primary table

otherwise you can write query like below

   declare @T table (id int)
   insert into @T  
      select AentryId form TableA where   class="10010" and AentryId in ( select BentryId from tableB)

  delete form TableA where  AentryId in ( select id from @T)
  delete form TableB where  BentryId in ( select id from @T)
Pranay Rana
This does meet the requirement: it needs to delete from table B as well.
APC
Thanks for your query. But it is deleting the rows from TableA only not from TableB...
Gnaniyar Zubair
query is modified hope this will work for you
Pranay Rana
+2  A: 

The easiest way to do this is through a foreign key defined with CASCADE DELETE:

alter table B 
  add constraint b_a_fk foreign key (BentryId)
  references A (AentryId)
  on delete cascade
/

If you delete a row from A all its dependent records in B are automatically deleted.

Of course, enforcing a foreign key means that you cannot create any rows in B with a BentryId which does not reference a pre-existing AentryId in A. This is normally a desirable thing but not every data model enforces relational integrity.

edit

Dropping the constraint really couldn't be simpler...

alter table B 
  drop constraint b_a_fk 
/
APC
i have altered my table as you said. But now i want to remove the constraint for some reason...how to do that?your swift action shall be highly appreciated.
Gnaniyar Zubair