2

我是存储过程的新手,所以我需要你们的帮助,我有三个表 Event_Session、Event_Speaker、Session_Speaker。我想通过传递 Event_session_id 删除 Event_Session Record 它还应该同时删除 Session_Speaker 和 Event_Speaker Record,请帮助我!这是表格

Event_Session(带字段的表)

Event_Session_Id、Session_name、Session_Description、标签

导航属性:Session_Speaker

Session_Speaker(带字段的表)

Event_Session_Id、Event_Speaker_Id、created_date

导航属性:Event_Session , Event_Speaker

Event_Speaker(带字段的表)

Event_Speaker_Id、Speaker_name、Created_date

导航属性:Session_Speaker

4

2 回答 2

4

您实际上需要从表中触发操作:DELETEEvent_Session

delimiter $$
CREATE TRIGGER Event_Session_Trigger
AFTER delete ON Event_Session
FOR EACH ROW
BEGIN

    DELETE FROM Event_Speaker ss 
    WHERE 
      ss.Event_Speaker_Id = (
           SELECT
              Event_Speaker_Id
           FROM Session_Speaker es
           WHERE
              es.Event_session_id = old.Event_session_id
      )

    DELETE FROM Session_Speaker  es 
    WHERE 
      es.Event_session_id = old.Event_session_id        

END$$
delimiter ;

更新:根据要求,同义词程序:

DELIMITER // 
CREATE PROCEDURE Event_Session_Procedure(IN Event_Session_Id_Delete INT) 
BEGIN 
    DECLARE Event_Speaker_Id_Delete INT;

    SELECT
      Event_Speaker_Id INTO Event_Speaker_Id_Delete
    FROM Session_Speaker es
    WHERE
      es.Event_session_id = Event_Session_Id_Delete

    DELETE FROM Event_Session e
    WHERE 
      e.Event_session_id = Event_Session_Id_Delete

    DELETE FROM Session_Speaker  es 
    WHERE 
      es.Event_session_id = Event_Session_Id_Delete

    DELETE FROM Event_Speaker ss 
    WHERE 
      ss.Event_Speaker_Id = Event_Speaker_Id_Delete

END // 
DELIMITER ; 

您可以通过运行CALL Event_Session_Procedure(123);where 123 is Event_Session_Idthat you want to delete来执行它

于 2013-06-06T07:26:31.067 回答
1

实际上你可以在没有触发器的情况下做到这一点,对于初学者,我建议你用更简单的方法来做

如果您可以返回原始脚本或生成新的查询页面并尝试此操作

首先要注意您设置的任何主键和外键约束,但在 ON DELETE CASCADE 中这些简单类型的声明的最后

这是我的一个数据库脚本中的一个示例

ALTER TABLE (YOUR TABLE NAME) ADD CONSTRAINT (your column_fk FOREIGN KEY (your column) REFERENCES YOUR TABLE(YOUR COLUMN) ON DELETE CASCADE; GO

这样您就可以更轻松地遵循我写的内容,这是直接来自我的数据库脚本的示例

ALTER TABLE TEAMS ADD CONSTRAINT DID_fk FOREIGN KEY (DID) REFERENCES DEVELOPERS(DID) ON DELETE CASCADE; 去

级联所做的只是遍历数据库的其余部分并删除对已删除项目的所有其他引用,以便您可以保持引用完整性

于 2013-06-06T08:12:50.727 回答