如何在Oracle中添加时间查询?

时间:2018-04-08 08:32:55

标签: sql oracle

CREATE TABLE Appointment

(

appointID INTEGER,

appoint_date DATE,

appoint_time  TIME,

appoint_type VARCHAR(5),

primary key (appointID)

);

INSERT INTO Appointment VALUES(1, '15-Apr-2017', '10:00', 'long');

INSERT INTO Appointment VALUES(2, '15-Apr-2017', '10:30', 'short');

INSERT INTO Appointment VALUES(3, '28-May-2017', '14:00', 'long');

INSERT INTO Appointment VALUES(4, '20-May-2017', '15:00', 'short');

INSERT INTO Appointment VALUES(5, '11-May-2017', '10:30', 'long');

INSERT INTO Appointment VALUES(6, '26-Jun-2017', '9:30', 'short');

INSERT INTO Appointment VALUES(7, '30-Jun-2017', '14:00', 'long');

INSERT INTO Appointment VALUES(8, '30-Jun-2017', '15:30', 'short');

INSERT INTO Appointment VALUES(9, '28-Apr-2017', '16:00', 'short');

INSERT INTO Appointment VALUES(10,'30-Apr-2017', '13:00', 'short');

当我尝试添加TIME时,我一直收到此错误:

Error starting at line : 24 in command -

CREATE TABLE Appointment(

appointID INTEGER,

appoint_date DATE,

appoint_time  TIME,

appoint_type VARCHAR(5),

primary key (appointID)

)

Error report -

ORA-00902: invalid datatype

00902. 00000 -  "invalid datatype"

*Cause:    
*Action:

我还试图添加我的DOCTOR TABLE,但我一直收到错误报告

ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"
*Cause:    
*Action:**

create table Doctor

(

    appointID   INTEGER     not null,

    regnum  CHAR(6),   

    doc_name    VARCHAR(40),

    doc_gender  CHAR(1),

    qual    VARCHAR(80),   

    foreign key (appointID) references Appointment

    primary key (appointID, regnum)

);

2 个答案:

答案 0 :(得分:1)

以下是我的建议:避免使用CHAR数据类型,除非它有意义(例如性别,就像你做的那样),以及VARCHAR> >>使用VARCHAR2代替(个人而言,我从不使用CHAR,并且从未使用过VARCHAR)。

DATE数据类型包含日期和时间组件,因此如果您使用它,您将非常安全。

制定主键约束的列不必指定NOT NULL约束,因为无论如何主键都不允许空值。

所以,这是一个有效的例子:

SQL> create table appointment
  2    (appointid    integer constraint pk_app primary key,
  3     appoint_date date,
  4     appoint_type varchar2(5)
  5    );

Table created.

SQL>
SQL> insert into appointment values
  2    (1, to_date('15.04.2017 10:00', 'dd.mm.yyyy hh24:mi'), 'long');

1 row created.

SQL>
SQL> create table doctor
  2    (appointid   integer constraint fk_doc_app references appointment (appointid),
  3     regnum      varchar2(6),
  4     doc_name    varchar2(40),
  5     doc_gender  char(1),
  6     qual        varchar2(80),
  7     --
  8     constraint pk_doc primary key (appointid, regnum)
  9    );

Table created.

SQL>

答案 1 :(得分:0)

没有名为' TIME'的数据类型,您可以使用时间戳:

CREATE TABLE Appointment
(
appointID INT,
appoint_date DATE,
appoint_time timestamp ,
appoint_type VARCHAR(5),
primary key (appointID)
);

对于插入,你必须使用TO_DATE和TO_TIMESTAMP函数,因为你插入的是string。:

INSERT INTO Appointment VALUES(3, To_date('15-Apr-2017','DD-MON-YY'), TO_TIMESTAMP('10:00','HH24:MI'), 'long');

http://sqlfiddle.com/#!4/59f5ef