【问题标题】:limit column char trigger plsql限制列char触发器plsql
【发布时间】:2020-04-21 21:35:53
【问题描述】:

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

我的桌子:

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;

【问题讨论】:

    标签: sql oracle plsql database-trigger create-table


    【解决方案1】:

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

    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,如果您的数据包含多字节字符,这可能会产生令人惊讶的行为

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

    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;
    

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

    【讨论】:

      【解决方案2】:

      使用check 约束:

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

      触发器不合适。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        相关资源
        最近更新 更多