我不明白为什么我的查询没有返回任何内容:
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);
请帮我理解。谢谢。
答案 0 :(得分:4)
正如评论中已经提到的,您需要使用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'
答案 1 :(得分:0)
OP中声明的另一个难点
select * from emp where hiredate between to_date ('01/01/81',
'mm/dd/yy') and to_date ('12/31/81', 'mm/dd/yy');
是hiredate
可以包含时间部分。鉴于样本数据,它没有,但没有什么能阻止它发生。考虑到这一点,一个更好的方法 - 比使用BETWEEN
更好 - 将如下:
SELECT * FROM emp
WHERE hiredate >= DATE'1981-01-01'
AND hiredate < DATE'1982-01-01';
还可以使用TRUNC()
:
SELECT * FROM emp
WHERE TRUNC(hiredate, 'YEAR') = DATE'1981-01-01';
我现在没有理由使用TO_DATE()
,因为Oracle支持ANSI日期文字(自9i以来)。