我是存储过程的新手,所以我需要你们的帮助,我有三个表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,Tags
导航属性: 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
答案 0 :(得分:4)
您实际上需要DELETE
来自Event_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);
您可以通过运行Event_Session_Id
来执行它,其中123是您要删除的{{1}}
答案 1 :(得分:1)
实际上你可以在没有触发器的情况下做到这一点,对于初学者我建议你这样做更容易
如果您可以返回原始脚本或生成新的查询页面并尝试此
首先要注意您设置的任何主键和外键约束 但在ON DELETE CASCADE
中声明这些简单类型的最后这是我的一个数据库脚本
的示例ALTER TABLE(你的桌子名称) 添加约束(您的column_fk FOREIGN KEY(您的列)在DELETE CASCADE上引用您的表(您的列); GO
这样你就可以更容易地遵循我所写的内容,这是一个直接来自我的数据库脚本的例子
ALTER TABLE TEAMS 添加约束DID_fk FOREIGN KEY(DID)参考开发者(DID)删除CASCADE; GO
cascade执行的操作只是通过数据库的其余部分并删除对已删除项目的所有其他引用,以便您可以保持引用完整性