Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have three tables which are related togather.How should I delete those records.

pls give me suggestions

Thanks & regards
venkatesh
Posted

Hi Venkatesh,

If you have three tables then just analysis there primary and foreign key relationship with each other, even with other tables also if you get that P.K and F.K relation is exist only within these three tables then delete the record in reverse direction according FK to PK from the tables.Like If you enter data in Table1 and Primary Key(P.K) is Foreign Key(F.K) of Table 2 and Then P.K of Table 2 is F.K of Table 3 the delete data as given below

<b>Table 3---> Table 2------> Table 1 </b>


Thanks & Regards :-D
abhi.22web.net
 
Share this answer
 
Delete from the lowest level up, transaction controlled

In this example, the 'Orders' table is related to 'Order Catalogue Details' which is related to 'Order Quantities'.

If you're using SQL 2005 then obviously try-catch rather than this type of error checking

SQL
--We're deleting from multiple tables, so trans control
BEGIN TRANSACTION

--Lowest level first, attempt to delete the order quantities
    DELETE FROM order_quantities WHERE oq_catalogue_id_fk IN (SELECT ocd_id_pk FROM order_catalogue_details WHERE ocd_order_id_fk = @OrderID)
    IF  (@@Error !=0)
    BEGIN
        ROLLBACK TRANSACTION
        RETURN @@ERROR
    END

--Now delete all the catalogue items for the order
    DELETE FROM order_catalogue_details WHERE ocd_order_id_fk = @OrderID
    IF  (@@Error !=0)
    BEGIN
        ROLLBACK TRANSACTION
        RETURN @@ERROR
    END

--remove the main order information
    DELETE FROM orders WHERE ord_id_pk = @OrderID
    IF  (@@Error !=0)
    BEGIN
        ROLLBACK TRANSACTION
        RETURN @@ERROR
    END

COMMIT TRANSACTION
 
Share this answer
 
If you define the relations between the tables with 'Cascade Delete Related records' a single delete could be enough. Otherwise you could use a stored procedure to perform the three delete statements.
 
Share this answer
 

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