2

I am trying to fetch records from the table using the below sql query.

SELECT Code,Description FROM Table
WHERE ID= 1 AND FromDate >= '2010-02-14' AND ToDate <= '2012-03-14'

Even though records exists for this date, query returns nothing.

ID HID HCode HDescription FromDate            ToDate 
-------------------------------------------------------------------
1  3   H8    New Year     2012-03-14 12:38:00 2012-03-14 12:38:00

Please give me a suitable solution. Thanks for your time !!

20
  • Can you post your table design? Commented Mar 20, 2012 at 7:59
  • 4
    Can you show us the FromDate and ToDate for the record with ID=1? Commented Mar 20, 2012 at 7:59
  • 2
    @RoyiNamir - YYYY-MM-DD is safe for date but not for datetime. Have a look here. Commented Mar 20, 2012 at 8:22
  • 2
    @RoyiNamir - You've misread (as I almost did). It says My SQL Server Wishlist, not My SQL Server Wishlist. Commented Mar 20, 2012 at 9:06
  • 1
    @RoyiNamir - the T is what makes that safe. Remove the T and it will fail. Commented Mar 20, 2012 at 9:12

5 Answers 5

2

try this :

declare @dayAfter datetime     --let take 1 day after

set @dayAfter = DateAdd(day,1,'20120314')

SELECT Code,Description FROM Table
WHERE ID= 1 AND 
FromDate >= '20100214' AND 
ToDate <  DateAdd(day, DateDiff(day, 0, @dayAfter ), 0)

p.s :

DateAdd(day, DateDiff(day, 0, @dayAfter ), 0) will reset time to 00:00

so you need desired EndTime < begining of the day after

Sign up to request clarification or add additional context in comments.

1 Comment

@SyedIbrahim youre welcome. please also read the conversation between me and marc and mikael. there were some important points to notice about. ( and learn [also for me])
1

Try with following query,it will definately solve your problem....

SELECT Code,Description FROM Table
   WHERE ID= 1 AND
         CONVERT(VARCHAR(10), FromDate, 101)>= CONVERT(VARCHAR(10),CAST('2010-02-14' AS DATETIME),101) AND 
         CONVERT(VARCHAR(10), ToDate, 101)<= CONVERT(VARCHAR(10),CAST('2012-03-14' AS DATETIME),101) ;

Comments

0

If you select data between FromDate and ToDate then remove ID=1. Аs in this case is selected record with ID = 1 and FromDate and ToDate checked this entry.

Comments

0

You are selecting data from ragne

FromDate >= '2010-02-14 00:00:0000' AND ToDate <= '2012-03-14 00:00:0000'

You should do like this:

FromDate >= '2010-02-14' AND ToDate < '2012-03-15'

Comments

0
SELECT *
 FROM  table
 WHERE year_date BETWEEN FromDate AND ToDate

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.