gpt4 book ai didi

sql - Oracle SQL 日期间查询

转载 作者:行者123 更新时间:2023-12-04 14:29:07 25 4
gpt4 key购买 nike

我不明白为什么我的查询没有返回任何内容:

 select * from emp where hiredate between to_date ('01/01/81',
'mm/dd/yy') and to_date ('12/31/81', 'mm/dd/yy');

这是表的结构:
CREATE TABLE EMP ( 
EMPNO NUMBER(4) NOT NULL,
ENAME CHAR(10),
JOB CHAR(9),
MGR NUMBER(4) CONSTRAINT EMP_SELF_KEY
REFERENCES EMP (EMPNO),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2) NOT NULL,
CONSTRAINT EMP_FOREIGN_KEY FOREIGN KEY (DEPTNO) REFERENCES DEPT (DEPTNO),
CONSTRAINT EMP_PRIM_KEY PRIMARY KEY (EMPNO));

INSERT INTO EMP VALUES (7839,'KING','PRESIDENT',NULL,'17-NOV-1981',5000,NULL,10);
INSERT INTO EMP VALUES (7698,'BLAKE','MANAGER',7839,'1-MAY-1981',2850,NULL,30);
INSERT INTO EMP VALUES (7782,'CLARK','MANAGER',7839,'9-JUN-1981',2450,NULL,10);
INSERT INTO EMP VALUES (7566,'JONES','MANAGER',7839,'2-APR-1981',2975,NULL,20);
INSERT INTO EMP VALUES (7654,'MARTIN','SALESMAN',7698,'28-SEP-1981',1250,1400,30);
INSERT INTO EMP VALUES (7499,'ALLEN','SALESMAN',7698,'20-FEB-1981',1600,300,30);
INSERT INTO EMP VALUES (7844,'TURNER','SALESMAN',7698,'8-SEP-1981',1500,0,30);
INSERT INTO EMP VALUES (7900,'JAMES','CLERK',7698,'3-DEC-1981',950,NULL,30);
INSERT INTO EMP VALUES (7521,'WARD','SALESMAN',7698,'22-FEB-1981',1250,500,30);
INSERT INTO EMP VALUES (7902,'FORD','ANALYST',7566,'3-DEC-1981',3000,NULL,20);
INSERT INTO EMP VALUES (7369,'SMITH','CLERK',7902,'17-DEC-1980',800,NULL,20);
INSERT INTO EMP VALUES (7788,'SCOTT','ANALYST',7566,'09-DEC-1982',3000,NULL,20);
INSERT INTO EMP VALUES (7876,'ADAMS','CLERK',7788,'12-JAN-1983',1100,NULL,20);
INSERT INTO EMP VALUES (7934,'MILLER','CLERK',7782,'23-JAN-1982',1300,NULL,10);

请帮我理解。谢谢你。

最佳答案

正如评论中已经提到的,您需要使用 RR格式as documented here ,或者可能更好,使用 4 位数年份。 Wernfried给出的例子在评论中:

  • to_date ('01/01/81', 'mm/dd/rr')
  • to_date ('01/01/1981', 'mm/dd/yyyy')

  • 但是,如果您真的不需要进行任何格式化,我强烈建议您不要使用 Oracle 的格式化功能。改写这个:
    select * from emp 
    where hiredate between date '1981-01-01' and date '1981-12-31';

    以上是 SQL 标准的日期字面量表达方式,Oracle 也支持。它比格式化字符串更容易记住,并且它独立于您的区域设置/语言等。

    如果你想对时间戳做同样的事情,也有时间戳文字:
    where hiredate between timestamp '1981-01-01 00:00:00.0'
    and timestamp '1981-12-31 23:59:59.999'

    关于sql - Oracle SQL 日期间查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653042/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com