Oracle使用虚拟列创建表

时间:2013-03-14 08:12:43

标签: sql oracle

我在Oracle上运行此SQL(Oracle Database 11g企业版11.1.0.7.0 - 64位生产):

CREATE TABLE R_SEQUENCES_COUNT1
  (
    DS_ID NUMBER,
    LINE_TIME TIMESTAMP(6),
    DAY_ID  DATE GENERATED ALWAYS   AS (TRUNC(LINE_TIME)),
    HOUR_ID  DATE GENERATED ALWAYS  AS (TRUNC(LINE_TIME,'HH24')) ,
    MINUTE_ID DATE GENERATED ALWAYS AS (TRUNC(LINE_TIME,'MI')) ,
    SECOND_ID DATE GENERATED ALWAYS AS (LINE_TIME),
    R_ID       NUMBER,
    SEQUENCE_ID NUMBER
  )NOLOGGING
  TABLESPACE TWC_DATA_SPACE
  PARTITION BY LIST (DS_ID)
  SUBPARTITION BY LIST(DAY_ID)
  (PARTITION DS_ID_OTHER VALUES (DEFAULT) 
  (SUBPARTITION DS_ID_OTHER_DAY_ID_OTHER VALUES (DEFAULT)))

并得到此错误:

Error at Command Line:8 Column:40
Error report:
SQL Error: ORA-54016: Invalid column expression was specified

出了什么问题?

2 个答案:

答案 0 :(得分:1)

您希望将其作为日期使用:

SECOND_ID DATE GENERATED ALWAYS AS (cast(LINE_TIME as date)),

否则你可以这样做:

SECOND_ID TIMESTAMP GENERATED ALWAYS AS (LINE_TIME + numtodsinterval(0, 'day')),

虽然在那种情况下不确定为什么你想要一个精确的列副本?

例如,对于第二个:

SQL> CREATE TABLE R_SEQUENCES_COUNT1
  2    (
  3      DS_ID NUMBER,
  4      LINE_TIME TIMESTAMP(6),
  5      DAY_ID  DATE GENERATED ALWAYS   AS (TRUNC(LINE_TIME)),
  6      HOUR_ID  DATE GENERATED ALWAYS  AS (TRUNC(LINE_TIME,'HH24')) ,
  7      MINUTE_ID DATE GENERATED ALWAYS AS (TRUNC(LINE_TIME,'MI')) ,
  8      SECOND_ID TIMESTAMP GENERATED ALWAYS AS (LINE_TIME+numtodsinterval(0, 'day')),
  9      R_ID       NUMBER,
 10      SEQUENCE_ID NUMBER
 11    )NOLOGGING
 12  /

Table created.

SQL> insert into  R_SEQUENCES_COUNT1 (ds_id, line_time) values (1, systimestamp);

1 row created.

SQL> @print_Table "select * from  R_SEQUENCES_COUNT1"
DS_ID                         : 1
LINE_TIME                     : 14-mar-2013 09:56:31.104921
DAY_ID                        : 14-mar-2013 00:00:00
HOUR_ID                       : 14-mar-2013 09:00:00
MINUTE_ID                     : 14-mar-2013 09:56:00
SECOND_ID                     : 14-mar-2013 09:56:31.104921
R_ID                          :
SEQUENCE_ID                   :
-----------------

答案 1 :(得分:0)

在你的创作中

//set condition is invalid
SECOND_ID DATE GENERATED ALWAYS AS (LINE_TIME)



// change to this...
SECOND_ID DATE GENERATED ALWAYS AS (TIMESTAMP)

数据类型TIMESTAMP允许几分之一秒。如果将其转换为DATE,则将删除小数秒 - 例如

所以选择SECONDS ..

select cast(systimestamp as date) from dual;

我认为的另一种方式是......

TRUNC()时间戳到秒,你可以把它投到日期

CAST( timestamp AS DATE)

然后执行TRUNC,如:

TRUNC(CAST(timestamp AS DATE), 'YEAR')