限制列char触发plsql

limit column char trigger plsql

我开始学习 PLSQL 并创建了一个非常非常简单的 table,我正在尝试熟悉函数和触发器。

我的table:

create table customer(
f_name varchar(30) not null,
s_name varchar(30) not null,
passwd varchar(20) not null,
constraint customer_f_name_pk primary key (f_name));

现在问题来了,我想在插入或更新新行(biuefer)之前进行限制,以便名字必须是 8 个字符,不能少也不能多。如果您尝试插入名称少于或多于 8 个字符的行,我希望打印出一条消息。

create or replace trigger biufer_customer
before insert or update
of f_name
on customer
for each row
begin
    *NO IDEA WHAT TO TYPE*
    raise_application_error(-20001,'So I type my text here');
end;

使用check约束:

alter table biufer_customer add constraint chk_customer_f_name
    check (length(f_name) = 8);

触发器不合适。

如果你想实现这样的约束,你通常会使用检查约束而不是触发器:

create table customer(
    f_name varchar2(8 char) not null check(length(f_name) = 8))
    s_name varchar2(30 char) not null,
    passwd varchar2(20 char) not null,
    constraint customer_f_name_pk primary key (f_name)
);

备注:

  • 如果您不允许超过 8 个字符,那么声明 varchar(30) 是没有意义的,所以我缩小了

  • 你想要 varchar2 而不是 varchar(在新代码中推荐使用此 Oracle 数据类型)

  • 您应该使用 char 声明列的长度 - 默认值为 byte,如果您的数据具有多字节字符[=19],这可能会产生令人惊讶的行为=]

但是由于您解释说您正在玩弄游戏并想了解如何使用触发器来实现这一点,因此代码如下所示:

create or replace trigger biufer_customer
before insert or update
of f_name on customer
for each row
begin
    if (length(:new.f_name) <> 8) 
        then raise_application_error(-20001,'So I type my text here');
    end if;
end;

在触发器代码中,您可以使用伪table :new 来访问当前正在更新或插入的值;您可以将支票包装在 if 语句中并相应地引发错误。