[英]How to create SQL Trigger to enter a new values into another table if value to be entered doesn't previously exist?
I'm working with Oracle SQL, and I have two tables. 我正在使用Oracle SQL,并且有两个表。 A table of conversations and a table of messages, and a message can't be added unless a conversation exists first.
对话表和消息表,除非首先存在对话,否则无法添加消息。 So when a new message wants to be added to the message table, I need to have a trigger to check is a conversation for that message exists yet or not, and if it doens't it will add a new conversation values to the conversation table for the message.
因此,当要将新消息添加到消息表中时,我需要触发一个触发器来检查该消息是否存在对话,如果不存在,它将在对话表中添加新的对话值消息。 "Warning: Trigger created with compilation errors."
“警告:触发器因编译错误而创建。” But I don't seem to see my error.
但是我似乎看不到我的错误。 I was hoping to get any insight here on what I can do to make this code work better.
我希望在这里可以做些什么使我的代码更好地工作的见解。
CREATE OR REPLACE TRIGGER CreateConversation
BEFORE INSERT ON Messages
FOR EACH ROW
BEGIN
dbms_output.put_line('made it inside');
IF NOT EXISTS (select * FROM Conversation WHERE convID = new.convID AND msgID = new.msgID )
THEN
dbms_output.put_line('Conversation does not exist!');
INSERT INTO Conversation VALUES(:new.convID, :new.msgID);
END IF;
END;
/
You can not use EXISTS
in PL/SQL; 您不能在PL / SQL中使用
EXISTS
。 if you need to check the existence of related records, try with something like this (not tested): 如果您需要检查相关记录的存在,请尝试以下类似方法(未经测试):
CREATE OR REPLACE TRIGGER CreateConversation
BEFORE INSERT ON Messages
FOR EACH ROW
declare
vCount number;
BEGIN
dbms_output.put_line('made it inside');
select count(1)
into vCount
FROM Conversation
WHERE convID = :new.convID
AND msgID = :new.msgID;
IF vCount = 0
THEN
dbms_output.put_line('Conversation does not exist!');
INSERT INTO Conversation VALUES(:new.convID, :new.msgID);
END IF;
END;
/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.