语法:
create [or replace] trigger trigger_name{before | after} trigger_event on table_name[for each row][when trigger_condition]trigger_body123456
我们对Snumber字段创建触发器使插入数据时自动生成随机数
create table Course(Cno char(10) primary key, -- 课程号 Cname varchar(20),-- 课程名 Cpno char(10),-- 先行课程号 Ccredit smallint,-- 学分 Snumber int-- 最大选课人数);1234567
如果创建触发器后还跟有sql语句请务必加上反斜线/
-- 实现Course表插入时Snumber生成随机数 create or replace noneditionable trigger random_snumber before insert on Coursefor each rowDECLARE next_snumber int;BEGIN -- 生成50-100的随机数 select dbms_random.value(50,100) into next_snumber from dual; :new.Snumber :=next_snumber;END;/123456789101112
测试数据
INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110001','Math',NULL,3);commit;INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110002','English','2',2);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110003','Chinese','4',3);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110004','Java',NULL,4);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110005','Python','6',3);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110006','Database',NULL,5);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110007','C','3',2);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110008','C++',NULL,3);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110009','JAVAWeb',NULL,4);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110010','Uml',NULL,5);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110011','Miniprogram',NULL,4);INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES('110012','Statistic','1',3);commit;1234567891011121314
信息加载中,请等待
微信客服(速回)
微信客服(慢回)