Wrox Home  
Search P2P Archive for: Go

  Return to Index  

sql_language thread: RE: How to DELETE from two connected tables?


Message #1 by "Maximilian Wilson" <wilsonm80@n...> on Mon, 17 Dec 2001 20:36:51
Jon wrote:
> I have found out what was going on - the trigger below (t_topics_Delete) 
> was somehow interfering.  I deleted the trigger, and the DELETE 
statement 
> worked, with no weird error message!
> 
> Now I have to figure out what the trigger was doing (I didn't write it), 
> and see what functionality has been lost by removing it and now has to 
be 
> replaced in some other way (that doesn't screw up the DELETE!)

> Create Trigger t_topics_Delete
> On dbo.t_topics
> For Delete
> As
> 	Declare @topic_id int
> 	select @topic_id = (select topic_parent from deleted)
> 	if @topic_id=-1 
> 		begin
***DELETE all topics which have this one as a parent***

> 			DELETE a FROM t_topics a , deleted b WHERE 
> (a.topic_parent = b.topic_id)		
> 		end
> 	else

***decrement topic_count for (all) parents of this topic***
> 		update a set a.topic_count = a.topic_count -1 from 
> t_topics a, deleted b where a.topic_id = b.topic_parent

I can tell you what was wrong:

SELECT @topic_id = (SELECT topic_parent FROM deleted)

expects a single value. However, since you specified 'Delete ...WHERE 
forum_id = 28', which is two different rows, it tries to set @topic_id to 
the set

(-1, 28) or something similar. 

As for how to fix it, it's really hard to say without knowing what 
topic_count means, or when topic_parent is -1 and why. I'm also suspicious 
of the trigger in that it doesn't delete children of the deleted record if 
topic_parent is not -1 (it exclusively decrements topic_count of *ITS* 
parent). Anyway, depending on what it's doing, you might just

ALTER TABLE t_topic
ADD CONSTRAINT FKtopic$has$parent foreign key (topic_parent)
   references t_topic(topic_id) on delete cascade

which forces all topics to have a topic_parent which is either NULL 
(presumably a root, and assuming that topic_parent is nullable) or a 
topic_id previously listed (or itself). When a topic is deleted, all child 
topics (as determined by topic_parent) and their children, etc. will be 
automatically deleted. Then you can skip the trigger.

--Wilson

  Return to Index