extract date only from given timestamp in oracle sql

前端 未结 7 1548
后悔当初
后悔当初 2021-02-13 05:34

The following query:

select cdate from rprt where cdate <= TO_CHAR(sysdate, \'YYYY/MM/DD-HH24-MI-SS-SSSSS\') and ryg=\'R\' and cnum=\'C002\';
<
相关标签:
7条回答
  • 2021-02-13 06:31

    This is exactly what TO_DATE() is for: to convert timestamp to date.

    Just use TO_DATE(sysdate) instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS').

    SQLFiddle demo

    UPDATE:

    Per your update, your cdate column is not real DATE or TIMESTAMP type, but VARCHAR2. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.

    You should convert your cdate VARCHAR2 field into real TIMESTAMP. Assuming there are no other users for this field except for your code, you can convert cdate to timestamp as follows:

    BEGIN TRANSACTION;
    -- add new temp field tdate:
    ALTER TABLE mytable ADD tdate TIMESTAMP;
    -- save cdate to tdate while converting it:
    UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');
    
    -- you may want to check contents of tdate before next step!!!
    
    -- drop old field
    ALTER TABLE mytable DROP COLUMN cdate;
    -- rename tdate to cdate:
    ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
    COMMIT;
    

    SQLFiddle Demo

    0 讨论(0)
提交回复
热议问题