Auto generate primary key as current date time in H2 database

时间:2015-06-30 13:26:47

标签: sql database timestamp primary-key h2

I have to create a table in H2 with primary key in yyyyMMddHHmmssSSS format.So that for every insert it automatically takes current date time in the mentioned format.

CREATE TABLE TEST_TABLE(ID BIGINT DEFAULT CURRENT_TIMESTAMP() PRIMARY KEY, NAME VARCHAR(255));

Problem is CURRENT_TIMESTAMP() format is yyyy-MM-dd HH:mm:ss.SSS.How can I get it in required format.

1 个答案:

答案 0 :(得分:2)

您可以在H2控制台中尝试:

call formatdatetime(now(),'yyyyMMddHHmmssSSS');

这将为您提供格式正确的字符串。现在你需要将它转换为bigint。

call cast(formatdatetime(now(),'yyyyMMddHHmmssSSS') as bigint);

最后一步:相应地更改SQL ...

CREATE TABLE TEST_TABLE(
  ID BIGINT DEFAULT CAST(FORMATDATETIME(CURRENT_TIMESTAMP(), 'yyyyMMddHHmmssSSS') AS BIGINT) PRIMARY KEY,
  NAME VARCHAR(255)
);

在H2 1.3和1.4上测试。

提醒:请使用交易并填充您的插入信息......