在CASE WHEN期间获取语法错误

时间:2017-11-22 12:01:52

标签: mysql jboss db2

我正在尝试在小型MYSQL查询下运行以创建表。

这是MYSQL查询:

CREATE TABLE SAMPLE_TEST (
  ID BIGINT ,
  TYPE INTEGER NOT NULL,
  TYPE2 GENERATED ALWAYS AS (CASE WHEN TYPE = 0 THEN ID ELSE TYPE END),
  PRIMARY KEY (ID)
  );

运行上述查询后,我收到以下错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GENERATED ALWAYS AS (CASE WHEN TYPE = 0 THEN ID ELSE TYPE END),
  PRIMARY KEY (I' at line 4

我在GENERATED ALWAYS AS数据库中使用DB2,我已从SQL syntax error 'GENERATED ALWAYS AS IDENTITY'更改为auto_increment

现在我想知道MySQL中是否存在CASE WHEN或MySQL的替代方案?任何帮助或建议?

2 个答案:

答案 0 :(得分:4)

在使用GENERATED ALWAYS之前使用数据类型。 你可以在下面的代码中使用所需的数据类型。

CREATE TABLE SAMPLE_TEST (
    ID BIGINT,
    TYPE INTEGER NOT NULL,
    TYPE2 DOUBLE GENERATED ALWAYS AS
        (CASE WHEN `TYPE` = 0 THEN `ID` ELSE `TYPE` END),
    PRIMARY KEY (ID)
)

Demo

答案 1 :(得分:1)

根据MySQL文档,您需要遵循以下语法

col_name data_type [GENERATED ALWAYS] AS(表达式)

所以,

NullPointerException

参考:https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html