SQL: comparing date with datetime field

I'm having a brain fart as I assume this is really simple.
Given that I have the date in the format of yyyy/mm/dd, how
do I put that
into a sql query that compares that to the datetime field?
It appears the datetime field, by default, uses this format:
m/d/yyyy
hh:mm:ss am
-Darrel

If your date formats are different you will have to use CAST
or CONVERT
functions as you state you already have. If this works then
stick with it.
You may also need to use a SET DATEFORMAT command. See below:
http://msdn2.microsoft.com/en-us/library/ms189491.aspx
Dates in SQL Server can be a bit of a pain to work with. It
is usually best
practice to store your DateTime data in raw format and use
CAST or CONVERT
functions in your Stored Procs to get the correct results.
Pat.
"darrel" <[email protected]> wrote in message
news:ftloim$jv4$[email protected]..
>
>> What dbms?
>
> t-sql (MSSQL)
>
> For now, via string functions, I rearrange the date/time
format manually,
> and then use the CAST statement in the SQL query. Not
pretty, but seems to
> work.
>
> -Darrel
>

Similar Messages

  • Performance question when compare date with date or char with char

    Hello from Germany (Frankfurt) !
    I am working on Oracle 9.2.0.8.0
    and have to solve following problem:
    Comparison of a date and char fields.
    Now two ways to do it.
    Either I compare char with char and convert date to char,
    or I compare date with date and convert char to date.
    Now the performace question. Which operation takes more effort for the database?
    So why not to try and to see the results?
    First create table:
    CREATE TABLE TEST (
    char_date VARCHAR2(8),
    real_date DATE
    NOLOGGING;
    Then insert 1.000.000 rows
    BEGIN
    for x in 1..1000000
    loop
    insert into test (char_date, real_date) VALUES('19990101', TO_DATE('2006.01.01', 'YYYY.MM.DD'));
    end loop;
    COMMIT;
    END;
    Collect statistics
    EXEC dbms_stats.gather_table_stats('TESTER', 'TEST');
    Now run some selects for date to char conversion:
    Elapsed: 00:00:00.00
    SQL> select * from test t where TO_DATE(char_date, 'YYYYMMDD') > real_date;
    no rows selected
    Elapsed: 00:00:03.02
    SQL> select * from test t where TO_DATE(char_date, 'YYYYMMDD') > real_date;
    no rows selected
    And some selects for char to date conversion:
    Elapsed: 00:00:03.02
    SQL> select * from test t where char_date > TO_CHAR(real_date, 'YYYYMMDD');
    no rows selected
    Elapsed: 00:00:02.05
    SQL> select * from test t where char_date > TO_CHAR(real_date, 'YYYYMMDD');
    no rows selected
    Elapsed: 00:00:02.05
    SQL>
    As you see when I compare char with char and convert date to char it seems to be faster (almost 1 second)
    Is the test correct?
    I still not sure, what gets better performance...
    Any idea?
    Thanks!

    Depends on whether you want the right results or not.
    Why don't you run the following two queries and see if the difference in results tells you anything?:
    with t as (select to_date('01/02/2007', 'dd/mm/yyyy') date_col from dual
               union all
               select to_date('02/02/2007', 'dd/mm/yyyy') from dual
               union all
               select to_date('03/02/2007', 'dd/mm/yyyy') from dual
               union all
               select to_date('03/03/2006', 'dd/mm/yyyy') from dual)
    select *
    from   t
    where  date_col < to_date('04/03/2006', 'dd/mm/yyyy');
    with t as (select to_date('01/02/2007', 'dd/mm/yyyy') date_col from dual
               union all
               select to_date('02/02/2007', 'dd/mm/yyyy') from dual
               union all
               select to_date('03/02/2007', 'dd/mm/yyyy') from dual
               union all
               select to_date('03/03/2006', 'dd/mm/yyyy') from dual)
    select *
    from   t
    where  to_char(date_col) < '04/03/2006';

  • Uploading of cost center data with additional fields

    Hi Gurus,
    I have uploaded the cost center data. now my client has given same data with additional fields data(ORT01, ORT02, TXJCD). first time I have uploaded with LSMW IDOC methos COSMAS1. but in the same idoc the extra field not available. So i have tried recording method for KS02 to upload the data. but the data is not changed. in the sence the additional fields data not loading. while uploading i getting the probelm at TXJCD. it is getting a popup window. i was not able to handle that. Is there any other Basic IDOC to upload the data with all the fields in cost center. BAPI or Direct input program? Thanks in advance

    hi,
    you can  avoid the popup screen by using  OK code.
    ~linganna.

  • Compare date with time

    Hi ,
    Oracle 10.2.0.1.0
    I need to compare date field with time stamp as well . I tried doing byt getting time stamp using to_char and on convertion into date by using to_date , I'm loosing time stamp please help

    804282 wrote:
    I need to compare date field with time stamp as well Compare how exactly?
    If you for example want to see if the date and timestamp are "equal", you can use the following approach - where in this specific approach it is deemed that if the difference between the timestamp and date is less than 1 sec, the two values are equal. E.g.
    SQL>
    SQL> create table test_tab(
      2          d       date,
      3          t       timestamp
      4  );
    Table created.
    SQL>
    SQL> insert into test_tab values( sysdate, systimestamp );
    1 row created.
    SQL> --// is the date and timestamp within 1 sec of one another?
    SQL> select * from test_tab where t-d <  to_dsinterval('0 0:0:1.00');
    D                   T
    2011/07/12 07:25:06 12/JUL/11 07:25:06.744832
    SQL> --// the reverse test
    SQL> select * from test_tab where t-d >=  to_dsinterval('0 0:0:1.00');
    no rows selected
    SQL>

  • Dynamic SQL and Data with Single Quotes in it.

    Hi There,
    I have a problem in that I am using dynamic SQL and it happens that one of the columns does contain single quotes (') in it as part of the data. This causes the resultant dynamic SQL to get confused as the single quote that is part of the data is taken to mean end of sting, when in fact its part of the data. This leaves out a dangling single quote that was meant to enclose the string. Here is my dynamic SQL and the result of the parsed SQL that I have captured:
    ****Dynamic SQL*****
    l_sql:='select NOTE_TEMPLATE_ID '||
    'FROM TMP_NOTE_TEMPLATE_VALUES '||
    'where TRIM(LEGACY_NOTE_CODE)='''||trim(fp_note_code)||''' '||
    'and TRIM(DISPLAY_VALUE)='''||trim(fp_note_text)||''' ';
    execute immediate l_sql INTO l_note_template_id;
    Because the column DISPLAY_VALUE contains data with single quotes, the resultant SQL is:
    ******PARSED SQL************
    select NOTE_TEMPLATE_ID
    FROM TMP_NOTE_TEMPLATE_VALUES
    where TRIM(LEGACY_NOTE_CODE)='INQ' and TRIM(DISPLAY_VALUE)='Cont'd'
    And the problem lies with the single quote between teh characters t and d in the data field for DISPLAY_ITEM. How can I handle this?
    Many thanks,

    I have been reliably informed that if one doesn't enclose char/varchar2 data items in quotes, the right indices may not be usedI am into oracle for past 4 years and for the first time i am hearing this.
    Your reliable source is just wrong. Bind variables are variables that store your value and which are used in SQL. They are the proper way to use values in your SQL. By default all variables in PL/SQL is bind variable.
    When you can do some thing in just straight SQL just do it. Dynamic SQL does not make any sense to me here.
    Thanks,
    Karthick.

  • Compare Date with Timezone

    Hi,
    I have a Date which is stored in the Database with the timezone like GMT, I have a java.util.Date which is selected in my UI from a Customized Calendar, I am converting this Date with timezone and want to compare this date with the date with timezone stored in the DB? How to accomplish this, please shed some light into this?
    Thanks.

    797836 wrote:
    I have a Date which is stored in the Database with the timezone like GMT, I have a java.util.Date which is selected in my UI from a Customized Calendar, I am converting this Date with timezone and want to compare this date with the date with timezone stored in the DB?As Parul said, Date does not involve a timezone. I think you need to clarify what you mean by "I am converting this Date with timezone", because it doesn't make much sense to me.
    BTW: If the date in your database is a standard SQL Date, then it will be converted to a java.sql.Date when you read it into Java with JDBC. And java.sql.Date is directly comparable with java.util.Date (in fact, it's a subclass).
    Winston

  • How to compare date with char

    hi
    i am having date from and date to feilds in my overtime element.i want to do the validation on these dates the the dates do not overlap or duplicated.the input value date from and date to are stored in database as varchar2 in the format yyyy/mm/dd 00:00:00. Now if i am trying to compare entered date with these dates i am getting literal does not match format string or date picture ends before....Can any body tell me what to do.
    Regards

    user10502390 wrote:
    hi
    i am having date from and date to feilds in my overtime element.i want to do the validation on these dates the the dates do not overlap or duplicated.the input value date from and date to are stored in database as varchar2 in the format yyyy/mm/dd 00:00:00. Now if i am trying to compare entered date with these dates i am getting literal does not match format string or date picture ends before....Can any body tell me what to do.
    RegardsPoint a) VERY BAD IDEA storing dates as VARCHAR2 on the database. It will only lead to corrupt data in the future.
    Point b) When comparing dates, you should compare them as DATE datatype as the database knows how to do comparisons against DATES. If you try and compare them as VARCHAR2 then you will most likely end up with incorrect comparisons.
    If you must have varchar2 storing of your dates/times (there's absolutely no reason to though)... you want...
    TO_DATE(:entered_date,'YYYY/MM/DD HH24:MI:SS') BETWEEN TO_DATE(DATEFROM,'YYYY/MM/DD HH24:MI:SS') AND TO_DATE(DATETO,'YYYY/MM/DD HH24:MI:SS')
    e.g.
    TO_DATE('20080815 13:23:33','YYYY/MM/DD HH24:MI:SS') BETWEEN TO_DATE(DATEFROM,'YYYY/MM/DD HH24:MI:SS') AND TO_DATE(DATETO,'YYYY/MM/DD HH24:MI:SS')

  • Compare date with timestamp

    I have data in timestamp format like 10/06/2009 11:59:01 PM EDT. I need to compare it with sysdate after removing the PM EDT etc.
    I tried to_date, trunc etc... nothing worked. Is there a way to remove that PM EDT and compare with sysdate.

    Hi,
    What problem you face when you directly compare timestamp column with sysdate?
    select cast (systimestamp as timestamp with local time zone) -sysdate from dual;
    CAST(SYSTIMESTAMPASTIMESTAMPWITHLOCALTIMEZONE)-SYSDATE
    +000000000 00:00:00.481609Regards
    Anurag Tibrewal.

  • How to compare date with null value

    Hi
    I have a date filed and i assigned that input box with context attribute of type Date.
    Here my problem is
    when the end user not entered any thing (null ) the i have give some defaul date.
    so first in the action method i have to check the date with null
    if it is null i have to give default date.
    so please let me know how to over come this.
    thanks
    Mukesh

    Hi
    You can get your date in your action method like
    Date newDate=new Date();
    Date myDate= wdThis
                              .wdGetYourComponentNameController()
                                      .wdGetContext()
                                           .currentYourNodeNameElement()
                                                           .getYourDateName();
    if ( myDate== null) {
             wdContext.currentContextElement().setYourDateName(newDate);
    else{...........//continue your other validations or calling other methods}
    Regards
    Abhijith YS
    Message was edited by:
            Abhijith YS

  • Sql Loader fails with newline fields

    Hi,I have a csv file delimited by "|" which is exported from MS Access. One of the fields contains a newline (e.g. notes column) which sql loader treats as beginning of new record. Can anyone tell me how to force the loader to ignore this newline.Is there a way I can tell the loader to read the optional '"' and continue with the record till it finds a closing '"'? Or is there a way to export data from access an force it to skip newlines and make a flat file with one record per line? I hate fixed length columns since it adds up pain in wrting the control files. Also the loader still fails to read the record if it encounters a newline as discussed above.
    Thanks

    Unfortunately there is no command that can make sql*loader treat two lines in a text file as one record. Some one asked tom kyte same question, see what he had to say about it:
    http://asktom.oracle.com/pls/ask/f?p=4950%3A8%3A%3A%3A%3A%3AF4950_P8_DISPLAYID%3A4972732303253
    Why don't you create a staging table where you first load the data, and then from the data inserted into this table populate your original table in the form required.
    Anwar

  • SQL compare DATE

    Hello,
    I know this isn't a SQL-forum but please help me:
    I want to select by a SQLStatement an object whose 'date' is like the
    'date' of today:
    String sqlStatement = "SELECT * FROM OBJECT WHERE DATE = " + todayDate;
    My question is:
    Which format shoud have 'todayDate'? I tried 2003-07-30 but it doesn't work. Then I tried '2003-07-30 00:00:00'. This does't work, too!
    PLEASE HELP!

    Probably not possible without knowing which database you are using.
    It would also help to know what you mean when you say it doesn't work. Does that mean it throws a SQL exception or that it doesn't return the results that you want.
    Of course you do realize that the field you are comparing to must be an exact match or this won't work. If the field also contains time values then you have to use a range comparison.

  • To compare date with another date in string in siebel bip report

    Hi,
    In my rtf I am comparing a Date1 with a date in string i.e. '10-NOV-14'. If Date1 is less than '10-NOV-14' I am dispalying a certain text and if not another text.
    This condition is working fine if Date1 have 2014 values but if  Date1 cointains 2015 date than the mentioned condition is falling.
    Kindly suggest any solutions.
    Regards,
    Siddhika

    This example may help:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:param name="currentDate"/>
        <xsl:variable name="firstDate" select="concat(substring($currentDate, 1,4),substring($currentDate, 6,2),substring($currentDate, 9,2))"/>
        <xsl:template match="/">
            <xsl:apply-templates select="//item"/>
        </xsl:template>
        <xsl:template match="item">
            <xsl:variable name="secondDate" select="concat(substring(submissionDeadline, 1,4),substring(submissionDeadline, 6,2),substring(submissionDeadline, 9,2))"/>
            <xsl:choose>
            <xsl:when test="$firstDate &gt; $secondDate">
                <xsl:call-template name="late"/>
                </xsl:when>
                <xsl:when test="$firstDate &lt; $secondDate">
                    <xsl:call-template name="ontime"/>
                </xsl:when>
                <xsl:when test="$firstDate = $secondDate">
                    <xsl:call-template name="same"/>
                </xsl:when>
                <xsl:otherwise>Monkeys<br /></xsl:otherwise>
            </xsl:choose>
        </xsl:template>
        <xsl:template name="ontime">
            This is on time
        </xsl:template>
        <xsl:template name="late">
            This is late
        </xsl:template>
        <xsl:template name="same">
            This is on time
        </xsl:template>
    </xsl:stylesheet>

  • How to Compare date with Current system date in XSLT mapping.

    Hello Experts
    In a XSLT mapping program, I hava a filed, ZZOB which is giving some date.
    which I need to compare with the current date.
    Condition-
    ZZOB is greater than current date or ZZOBLIG = NULL
    Then go further statements.
    how can i campare with the current date?
    Please help.
    Thanks
    Balaprasad

    This example may help:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:param name="currentDate"/>
        <xsl:variable name="firstDate" select="concat(substring($currentDate, 1,4),substring($currentDate, 6,2),substring($currentDate, 9,2))"/>
        <xsl:template match="/">
            <xsl:apply-templates select="//item"/>
        </xsl:template>
        <xsl:template match="item">
            <xsl:variable name="secondDate" select="concat(substring(submissionDeadline, 1,4),substring(submissionDeadline, 6,2),substring(submissionDeadline, 9,2))"/>
            <xsl:choose>
            <xsl:when test="$firstDate &gt; $secondDate">
                <xsl:call-template name="late"/>
                </xsl:when>
                <xsl:when test="$firstDate &lt; $secondDate">
                    <xsl:call-template name="ontime"/>
                </xsl:when>
                <xsl:when test="$firstDate = $secondDate">
                    <xsl:call-template name="same"/>
                </xsl:when>
                <xsl:otherwise>Monkeys<br /></xsl:otherwise>
            </xsl:choose>
        </xsl:template>
        <xsl:template name="ontime">
            This is on time
        </xsl:template>
        <xsl:template name="late">
            This is late
        </xsl:template>
        <xsl:template name="same">
            This is on time
        </xsl:template>
    </xsl:stylesheet>

  • Logic to compare date with standard timestamp

    Hi Experts,
    I want to retrieve the data which is "n" moths old.
    To compare that I want use only SYSDATE without timestamp.
    I want to use standard timestamp '23:59:59' along with SYSDATE.
    The condition should be as below.
    UPDATE_DATE <= ADD_MONTHS(15/01/2013 23:59:59,-3)
    UPDATE_DATE <= ADD_MOTHS(30/01/2013 23:59:59,-4)
    UPDATE_DATE<=ADD_MONTHS(sysdate||' '||'23:59:59',-3);Please help me how to implement it.
    Thanks in advance.

    973205 wrote:
    Thanks for your reply.
    Your query is not meeting my requirement.
    It just adding one day after it's adding months.
    TRUNC(sysdate) means it will truncate timestamp.
    I want to use standard timestamp along with sysdate.
    TRUNC(sysdate)||' '||'23:59:59' after that I want to add months.
    What you are trying to do is to concatenate a character string to a DATE value - which will not work and is not logical also..
    This can be achieved as below - minus 1 second from trunc(sysdate+1)
    select trunc(sysdate+1)-(1/(24*60*60)) dt
    from dual;
    DT                  
    03-Feb-2013 23:59:59   Your requirement is to filter as UPDATE_DATE<=ADD_MONTHS(sysdate||' '||'23:59:59',-3);
    This can be done as
    UPDATE_DATE<=ADD_MONTHS(trunc(sysdate+1)-(1/(24*60*60)),-3);The same thing can be achieved by replacing "<=" with "<" as
    UPDATE_DATE<ADD_MONTHS(trunc(sysdate+1),-3);Edited by: jeneesh on Feb 3, 2013 12:39 PM

  • How to compare date with thr current date

    Hi,
    I have an inout string which is in date format(dd/mm/yyyy hh:mm:ss) .
    what i need to do is comparing this date string with the current date. if my input string is less than current date , then display error message..
    how to do this?
    regards

    Excellent suggestions from all of you people!
    finally i got the solution
    code is:
    import java.util.*;
    import java.text.*;
    public class TestDate {
      public static void main(String args[]){
        TestDate a = new TestDate();
      TestDate() {
        String DATE_FORMAT = "dd/MM/yyyy hh:mm:ss";
         Date today = new Date();
         Date myDate=null;
        java.text.SimpleDateFormat sdf =
             new java.text.SimpleDateFormat(DATE_FORMAT);
         try{
         myDate = sdf.parse("01/06/2006 00:00:00");
         }catch(Exception e) {System.out.println(e);}
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(today);
        c2.setTime(myDate1);
        System.out.print(sdf.format(today));
        System.out.print(sdf.format(c1.getTime()));
        if (c1.before(c2)) {
           System.out.print(" is before ");
        if (c1.after(c2)) {
           System.out.print(" is after ");    
        if (c1.equals(c2)) {
           System.out.print(" same as ");    
    System.out.print(sdf.format(c2.getTime()));
      }

Maybe you are looking for

  • Media Encoder CS6 won't uprez alpha channels

    I have been trying to convert some files i created in both animation codec and AVID codec with alpha from 720p to 1080i/p but if i have the alpha set to rende, it creates a file with the video blown out and edges aliased. Same files if i turn the alp

  • Oracle 11g r1 install check fails on - Red Hat 5

    I'm getting the below check failures - Checking for glibc-devel-2.3.4-i386; Not found.     Failed <<<< Checking for glibc-devel-2.3.4-x86_64; Not found.     Failed <<<< Checking for gcc-c++-3.4.5; Not found.     Failed <<<< Everything else is ok, can

  • Trouble printing a password protected adobe document with hpeprint?

    How do I print a password protected Adobe document with hpeprint? I have an Officejet Pro 8600Plus

  • Problem with supsersedence

    Hi, I have a problem with supersedence. Client have win 7, office 2010, language pack and proofing tools. We want to upgrade to Office 365. Then we have to uninstall all Office 2010 products, and then install Office 365. I have used supersedence and

  • Output redirection

    The new JDeveloper only stores a small amount of the output in the message window. How do I change this to store all of it, or better yet, redirect System.err and/or System.out to a file? Also, the forum pages appear blank on my Mozilla Browser 10/19