Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Cascading Delete with single ID

Author  Topic 

bitse
Starting Member

1 Post

Posted - 2011-09-30 : 01:48:21
Hi,
am having my application for cascading delete on select the delete. Its dependency should delete completely.(PKey-PrimaryKey)(FKey- ForeignKey)

A(A-PKey)
|
B(A-FKey) C(A-FKey) D(A-FKey) E(A-FKey) F(A-FKey)
|
^
G(B-Fkey) H(B-Fkey) I(B-Fkey) J(B-Fkey) K(B-Fkey)

Like this my structure. I ll pass only the A table ID only . In B table having A table FKey. In G-Table only having Pkey ok B-Table.


My problem is For every Single A-Table ID i have Multiple B-Table values and same for G-Table . Please anyone help me to do this delete operation.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-30 : 02:18:56
the below query gives you reverse relationship starting from child nad moving up to parent tables based on fk relationships set. use this to delete the records starting from child tables upto root level.



;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),
0 as level
from sys.objects o
inner join sys.foreign_keys f
on f.parent_object_id = o.object_id
where o.is_ms_shipped=0
and o.type='u'
union all
select t.object_id as tblid,OBJECT_NAME(t.object_id) as tblname,o.tblid,o.tblname,o.level + 1
from object_cte o
inner join sys.foreign_keys f
on f.parent_object_id = o.tblid
join sys.objects t
on t.object_id = f.referenced_object_id
where t.is_ms_shipped=0
and t.type='u'

)
select * from
(
select row_Number() over (partition by tblname order by level) as rn,* from object_cte
)t
where rn=1
order by level




------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Snirk
Starting Member

2 Posts

Posted - 2011-09-30 : 03:22:04
You can use ON DELETE CASCADE Option when creating a reference between B and A, G and B. So you'll simply write DELETE FROM A, and all lines from all tables (B, G) would be deleted.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-30 : 03:57:22
thats fine when you're creating the fk. but if its not created with on delete cascade you might have to drop and recreate the fks

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -