Click here to Skip to main content
15,881,667 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
1st table name= tblA

fields:
ID int
NAME varchar

2nd table name = tblB

fields:
F int
eName varchar
ID int

3rd table name = tblC

fields:
G int
Gname varchar
ID int
F int




i have to delete ID from 3 tables where in three tables ID is same. if ID='1' in three tables the all record inside 3 tables should delete ..
please tell me...
Posted
Comments
[no name] 13-Dec-12 3:28am    
Can you please specify whether your 3 tables are inter related or not?
I mean to say is there any relation between your tables?
sreeCoderMan 13-Dec-12 3:31am    
yes you can see ID in three tables

You can include your delete statements in a transaction so that if anything goes wrong with any of the grouped statements, all changes will be aborted.

Here is how you will do it.
SQL
BEGIN TRY
  BEGIN TRANSACTION

    DECLARE @Id INT
    SET @Id = 1

    DELETE FROM tblC WHERE ID = @Id
    DELETE FROM tblB WHERE ID = @Id
    DELETE FROM tblA WHERE ID = @Id


  COMMIT TRANSACTION
 END TRY
 BEGIN CATCH
  ROLLBACK TRANSACTION
  --Exception handling
 END CATCH
 
Share this answer
 
1st table name= tblA

fields:
ID int
NAME varchar

2nd table name = tblB

fields:
F int
eName varchar
ID int

3rd table name = tblC

fields:
G int
Gname varchar
ID int
F int

Keep in mind always start deleting from bottom to top in this condition you have to delete first tblC record then tblB and then tblA

eg

delete from tblC where ID=Value
delete from tblB where ID=Value
delete from tblA where Id=Value

value must be common in all the field.
or
you can create procedure and just pass id of the record which you want to delete.

eg

Create procedure DemoDelete(@value int)
as
begin
delete from tblC where ID=@value
delete from tblB where ID=@value
delete from tblA where Id=@value
end
 
Share this answer
 
Comments
sreeCoderMan 13-Dec-12 4:22am    
shailendra patel can u show in a single line i mean not as in stored procedure
sreeCoderMan 13-Dec-12 5:06am    
this is usefull stored procedure ... i like it it works but actually i dont need in a stored procedure...
SQL
You cannot DELETE from multiple tables with a single expression in SQL 2005 - or any other standard SQL for that matter. 

The best method to get this effect is to specify FOREIGN KEYS between the table with an ON DELETE trigger.
 
Share this answer
 
Comments
sreeCoderMan 13-Dec-12 2:09am    
can you please write the code for me.....
[no name] 13-Dec-12 2:12am    
Even i m also trying the same thing..i got this much information till now so shared with u.as soon as i get solution will share.
and don't forget to vote for my answer..
sreeCoderMan 13-Dec-12 4:22am    
sure

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900