質問

I have a table structure having a EMP_DATE column as below

 ID       EMP_DATE
----    -----------
5400     14-FEB-2012

and i have inserted records into the table as below

INSERT INTO TEST_DATE VALUES(5400,SYSDATE);

After inserting records while i am trying to fetch the records of those who has EMP_DATE as SYSDATE its giving no rows selected. For time being let the SYSDATE be '01-JUL-2012`

 SELECT * FROM TEST_DATE WHERE EMP_DATE = SYSDATE;
                (OR)
 SELECT * FROM TESt_DATE WHERE EMP_DATE = '01-JUL-2012';

i was not able figure out any solution . Any suggestions would be helpful .

役に立ちましたか?

解決

The main problem is that a date includes hours, minutes and seconds, which you're not allowing for. If you want everything for a single day you can use the trunc function in order to get this:

SELECT * FROM TEST_DATE WHERE trunc(EMP_DATE) = trunc(SYSDATE);

By default trunc removes the time portion of a date, when operating on a date column. I would normally recommend a functional index on trunc(emp_date) in order to optimize this query. Something like:

create index i_test_date on test_date(trunc(emp_date));

I've built a little SQL Fiddle to demonstrate this.

There is an additional problem; though Oracle does support ANSI date literals your second query is wrong. Always, explicitly convert to a string to a date using the to_date function.

SELECT * FROM TEST_DATE WHERE EMP_DATE = to_date('01-07-2012','dd-mm-yyyy');

I've used the mm datetime format model instead of mon as there's no guarantee that JUL will always mean July; it depends on your NLS parameters, what "date language" your particular database or session is using. A datetime format model is how you tell the database the format of whatever string you're passing it to be converted into a date.


If you're interested the ANSI syntax for your second query would be:

SELECT * FROM TESt_DATE WHERE trunc(EMP_DATE) = DATE '2012-07-01'

It must be in this format (YYYY-MM-DD) to work.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top