0

I am having trouble trying to compare dates in my sql query:

SELECT restrictions, restrictions_adddate FROM restrictions WHERE id = '555555'
AND restrictions_adddate BETWEEN ? and ?;

Both of the parameters system print in the format 'mm-dd-yyyy'. I am getting a wrong date format error, but have tried doing it in multiple ways. Any help is appreciated, and if more info is needed, please let me know. thanks.

3
  • did you also try the format "yyyy-mm-dd"? Commented May 26, 2011 at 14:05
  • yes, I tried this as well, I get a literal does not match string error. Commented May 26, 2011 at 14:07
  • @a_horse_with_no_name , Oracle11g Commented May 26, 2011 at 14:22

3 Answers 3

1

This should work on any standard compliant DBMS:

SELECT restrictions, restrictions_adddate 
FROM restrictions 
WHERE id = '555555'
  AND restrictions_adddate BETWEEN DATE '2011-01-01' and DATE '2011-12-31';
Sign up to request clarification or add additional context in comments.

3 Comments

@Dems: that is not true. The format DATE '2011-01-01' is defined by the ANSI standard such that the literal is required to be in ISO format (yyyy-mm-dd). If you leave out the keyword DATE then you are absolutely right.
@a_horse_with_no_name: Actually it is true. SQL Server when in British English mode inteprets this format as 'yyyy-dd-mm' unless you add a time part e.g. "2012-07-13T00:00:00"
@Trekstuff: then SQL Server badly violates the standard.
0

This is my preference:

AND restrictions_adddate BETWEEN
    CONVERT(datetime, FLOOR(CONVERT(float, CAST('01-01-1900' AS DATETIME))))
    AND CONVERT(datetime, FLOOR(CONVERT(float, Getdate())));

This allows you to compare dates (minus the time stamps).

3 Comments

I tried this, but I am unfamiliar with most of the terms. How exactly is this comparing the dates?
He's taking a date with a time and removing the time part. which isn't really pasrt of your question.
@Dems, the questions was how to compare two dates. Regardless of whether I'm removing the time or not, that's what the code does. My example shows how to use the current date, as well as any date that you want to plug in as a string - '01-01-1900'.
0

Try checking out the CONVERT function T-SQL reference in BOL. You should be able to use this dictate the format of your dates.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.