如何在MySQL表中添加GENERATED BY DEFAULT AS IDENTITY?

时间:2017-12-04 16:21:03

标签: java mysql sql stored-procedures

我有一个DB2 Table,我正在尝试转换为MySQL表。这是DB2表:

CREATE TABLE MY_TABLE (
  ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1 NO MAXVALUE NO CYCLE CACHE 100),
  ACTIVE SMALLINT NOT NULL,
  PRIMARY KEY (ID)
)# 

我已转换为MySQL,如:

CREATE TABLE MY_TABLE (
  ID BIGINT ,
  ACTIVE SMALLINT NOT NULL,
  PRIMARY KEY (ID)
);

我正在运行一个程序

create procedure test_proced(
    in to_create bigint,
    out created bigint
)
begin
     set created = (select count(vnr.id) from MY_TABLE vnr);
    while (created < to_create) do
      insert into MY_TABLE (active) values(0);
      set created = created + 1;
    end while;
end;

但是在这张桌子上添加上述程序后,我收到了一些错误:

Caused by: java.sql.SQLException: Field 'id' doesn't have a default value

现在我怀疑GENERATED BY DEFAULT AS IDENTITY。这个错误是由于这个问题吗?如果是,如何转换为相应的MySQL表?

2 个答案:

答案 0 :(得分:3)

在MySQL中,您可以使用AUTO_INCREMENT

CREATE TABLE MY_TABLE (
  ID BIGINT NOT NULL AUTO_INCREMENT,
  ACTIVE SMALLINT NOT NULL,
  PRIMARY KEY (ID)
);

每次在ID中插入新行时,都会自动为列MY_TABLE生成新值。默认情况下,每个自动生成的值等于前一个(按插入顺序)记录加上1的值。

注意:默认设置是从1开始,步数为1

答案 1 :(得分:2)

将AUTO INCREMENT添加到主键可以解决此问题。