在 Oracle DB 中创建触发器以为单个列提供固定长度
Create trigger in Oracle DB to provide the fixed length for an individual column
在 table 名员工上创建触发器,应该:
数据插入命令触发
格式化 phone
字段,将其转换为模式 (YYY)XXX-XX-XX
。您输入的号码必须是10位。触发器应该检查这一点。如果数字有小于或大于10位数,则禁止数据插入并报错留言。
表格:
CREATE TABLE dept
(
dept_id number(3) not null,
dept_name varchar2(50) not null,
emp_cnt number(3) not null,
constraint dept_pk primary key (dept_id)
);
/
CREATE TABLE employees
(
emp_id number(3) not null,
dept_id number(3) not null,
emp_name varchar2(50) not null,
address varchar2(100),
phone varchar2(20) not null,
salary number(8,2) not null,
constraint emp_pk primary key (emp_id),
constraint dept_fk foreign key (dept_id) references dept(dept_id)
);
/
请帮帮我
使用 CHECK 约束不会解决您的问题,因为您必须屏蔽 Phone,最终将有超过 10 个数字。所以你必须在你的触发器中加入一个检查条件。要以所需格式屏蔽 phone 数字,您可以使用以下触发器 -
CREATE OR REPLACE TRIGGER trig_mask_phone
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF LENGTH(:new.phone) <> 10 THEN
RAISE_APPLICATION_ERROR(-20001, 'Phone No is incorrect');
END IF;
:new.phone := '(' || SUBSTR(:new.phone, 1, 3) || ')' || SUBSTR(:new.phone, 4, 3) || '-' || SUBSTR(:new.phone, 7, 2) || '-' || SUBSTR(:new.phone, 9, 2);
END;
/
在 table 名员工上创建触发器,应该:
数据插入命令触发
格式化 phone
字段,将其转换为模式 (YYY)XXX-XX-XX
。您输入的号码必须是10位。触发器应该检查这一点。如果数字有小于或大于10位数,则禁止数据插入并报错留言。
表格:
CREATE TABLE dept
(
dept_id number(3) not null,
dept_name varchar2(50) not null,
emp_cnt number(3) not null,
constraint dept_pk primary key (dept_id)
);
/
CREATE TABLE employees
(
emp_id number(3) not null,
dept_id number(3) not null,
emp_name varchar2(50) not null,
address varchar2(100),
phone varchar2(20) not null,
salary number(8,2) not null,
constraint emp_pk primary key (emp_id),
constraint dept_fk foreign key (dept_id) references dept(dept_id)
);
/
请帮帮我
使用 CHECK 约束不会解决您的问题,因为您必须屏蔽 Phone,最终将有超过 10 个数字。所以你必须在你的触发器中加入一个检查条件。要以所需格式屏蔽 phone 数字,您可以使用以下触发器 -
CREATE OR REPLACE TRIGGER trig_mask_phone
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF LENGTH(:new.phone) <> 10 THEN
RAISE_APPLICATION_ERROR(-20001, 'Phone No is incorrect');
END IF;
:new.phone := '(' || SUBSTR(:new.phone, 1, 3) || ')' || SUBSTR(:new.phone, 4, 3) || '-' || SUBSTR(:new.phone, 7, 2) || '-' || SUBSTR(:new.phone, 9, 2);
END;
/