Oracle date comparison in where clause

前端 未结 3 815
抹茶落季
抹茶落季 2021-01-06 05:05

For eg I have a student table with a DOJ(date of joining) column with its type set as DATE now in that I have stored records in dd-mon-yy format.

I have an IN param

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 05:41

    I have a student table with a DOJ(date of joining) column with its type set as DATE now in that I have stored records in dd-mon-yy format.

    Not quite, the DATE data-type does not have a format; it is stored internally in tables as 7-bytes (year is 2 bytes and month, day, hour, minute and second are 1-byte each). The user interface you are using (i.e. SQL/PLUS, SQL Developer, Toad, etc.) will handle the formatting of a DATE from its binary format to a human readable format. In SQL/Plus (or SQL Developer) this format is based on the NLS_DATE_FORMAT session parameter.

    If the DATE is input using only the day, month and year then the time component is (probably) going to be set to 00:00:00 (midnight).

    I have an IN param at runtime with date passed as string or say varchar and its in dd/mm/yyyy format. How do I compare and fetch results on date.?

    Assuming the time component for you DOJ column is always midnight then:

    SELECT COUNT(*)
    FROM   students
    WHERE  doj = TO_DATE( your_param, 'dd/mm/yyyy' )
    

    If it isn't always midnight then:

    SELECT COUNT(*)
    FROM   students
    WHERE  TRUNC( doj ) = TO_DATE( your_param, 'dd/mm/yyyy' )
    

    or:

    SELECT COUNT(*)
    FROM   students
    WHERE  doj >= TO_DATE( your_param, 'dd/mm/yyyy' )
    AND    doj <  TO_DATE( your_param, 'dd/mm/yyyy' ) + INTERVAL '1' DAY
    

提交回复
热议问题