簡體   English   中英

插入前觸發,插入后觸發

[英]Trigger before insert and trigger after insertion

我正在嘗試創建一個觸發器,以在DUMPINGGRD插入新行, DUMPINGGRD再插入REPORT 有用。 問題是創建的第一個FILE_ID DUMPINGGRD為“0”,當我嘗試插入另一行REPORT ,顯然它試圖創建File_Id為“0”一次。

CREATE TABLE REPORT ( R_Id int(10) NOT NULL AUTO_INCREMENT,
R_Type varchar(255) not null,
R_Title varchar(255) not null,
U_Id int(10) not null,
File_Id int(10) not null,  
PRIMARY KEY (R_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 CREATE TABLE `DUMPINGGRD`
(
`File_Id` int(10) NOT NULL,
`File_Name` varchar(255),
`UploadDate` date,
 PRIMARY KEY (`File_Id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE  `REPORT` ADD CONSTRAINT  `fk_report` FOREIGN KEY (`File_Id`)
REFERENCES `DUMPINGGRD` (`File_Id`) ON UPDATE CASCADE; 

delimiter $$
CREATE TRIGGER ins_File 
BEFORE INSERT ON `REPORT` 
FOR EACH ROW
BEGIN
INSERT INTO `DUMPINGGRD` (`File_Id`) VALUES (NEW.`File_Id`);
END$$
delimiter ;

謝謝!

當我嘗試插入新行REPORT ,我剛打了錯誤#1452 -不能添加或更新子行,外鍵約束失敗( pbreport ,約束fk_report外鍵( Doc_Id )參考dumpinggrdDoc_Id )ON更新級聯)”

我只是不知道怎么了。

嘗試這個:

   delimiter $$ CREATE TRIGGER ins_File BEFORE INSERT ON REPORT FOR EACH ROW BEGIN 
set @filenum=(Select max(File_Id) from DUMPINGGRD);  

if(@filenum=0) then  --checking whether record is present or not
begin
new.File_Id=1;--if no record is present then set file_id=1 
end;
else
new.File_Id=@filenum+1;--if record is present then set file_id=Maxvalue+1;
end if; 
    INSERT INTO DUMPINGGRD (File_Id) VALUES (NEW.File_Id);
     END$$ delimiter ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM