代码之家  ›  专栏  ›  技术社区  ›  netmajor

插入不带集合主列的行

  •  4
  • netmajor  · 技术社区  · 14 年前

    INSERT INTO GOST (ASSORTMENTID, ROZMIAR, GOST) 
    VALUES ( 54,'S','MjgwMzktODkgMTc0LTk2') 
    

    我想在表GOST中插入新行,但不想用主键-GOSTID指定列。我想让数据库设置下一个id值。 运行此代码时出现错误:

    GOSTID列的验证错误,值“ "

    可以在没有这个参数的情况下运行它吗?

    3 回复  |  直到 14 年前
        1
  •  3
  •   jachguate    14 年前

    我觉得一个剧本样本值1000多个字:

    转到firebird服务器计算机中的shell接口,cd到您具有读/写权限的文件夹,启动isql或isql fb(取决于您的系统和firebird版本),然后运行此脚本:

    create database 'netmajor.fdb' user 'sysdba' password 'masterkey';
    set autoddl off;
    
    create table netmajor_example (
        netmajor_id     integer not null
      , str_data        varchar(200)
      , int_data        integer
      , constraint pk_netmajor_example
          primary key (netmajor_id)
    );
    
    create generator netmajor_gen;
    
    set term ^;
    
    create trigger netmajor_pkassign
       for netmajor_example
    active before insert position 1
    AS
    begin
      if (new.netmajor_id is null) then
        new.netmajor_id = gen_id(netmajor_gen, 1);
    end
    ^
    
    commit work^
    
    set term ; ^
    
    
    insert into netmajor_example (str_data, int_data) values ('one', 1);
    insert into netmajor_example (str_data, int_data) values ('twenty', 20);
    commit work;
    
    select * from netmajor_example;
    

    看看结果,在我的机器里是:

    ; NETMAJOR_ID STR_DATA                     INT_DATA
    ;============ ============================ ============
    ;           1 one                                     1
    ;           2 twenty                                 20
    

    如果您有任何疑问,请随时与我们联系。谨致问候。

        2
  •  1
  •   marc_s    14 年前

    显然,你的主键是 不为空 列,也就是说,它总是必需的。你 不能 插入一行而不给出主键的值(除非它是由数据库系统自动设置的“自动编号”列)。

        3
  •  0
  •   Harriv    14 年前

    使用“插入前”触发器设置主键的值。Firebird没有“自动增量”字段类型,所以您需要自己处理它。

    http://www.firebirdfaq.org/faq29/ 学习如何做到这一点。一些数据库应用程序(如数据库工作台)可以自动创建触发器和生成器。