Wednesday, November 9, 2011

Recursive delete from parent child tables

Quite often there are cases where we will have set of tables linked by means of foreign key relationships. Deleting from one among such tables can be a real pain especially when it having lots of direct and indirect dependencies on child tables. In such cases, we need to start deleting dependent records from child tables back to parent recursively. The below code will help us in finding out recursively the object relationships and then delete from tables the dependent records

;with object_cte(tblid,tblname,rtblid,rtblname,level)

as

(

select distinct o.object_id as tblid,OBJECT_NAME(o.object_id) as tblname,cast(null as int),cast(null as sysname),