Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,
I want to know the below date format in sql server
how to find the record date between reverse date in sql
i have return below code but its showing no record

SQL
declare @frdate datetime, @todate datetime
select @frdate='2016-04-01', @todate ='2015-12-01'
select billdate from test where @frdate between @frdate and @todate order by billdate asc


but when i execute below code its working fine,

SQL
declare @frdate datetime, @todate datetime
select @frdate='2015-12-01', @todate ='2016-04-01'
select billdate from test where @frdate between @frdate and @todate order by billdate  asc


please let me know where i made a mistake,


thanks in advance.

What I have tried:

how to find the record date between reverse date in sql
Posted
Updated 26-Apr-16 8:28am
v4
Comments
ZurdoDev 26-Apr-16 9:47am    
What do you mean by reverse date? I don't think that is what you mean.

However, your where is wrong. You have
where @frdate between @frdate and @todate

which will always return true. It should be
where date_field_from_table between @frdate and @todate

You can not find records with reverse date, from date should be less then todate always.

if you want todate records in reverse date then you should use "order by desc" like below query:

SQL
declare @frdate datetime, @todate datetime
select @frdate='2015-12-01', @todate ='2016-04-01'
select billdate from test where @frdate between @frdate and @todate order by billdate desc


Ashish Nigam
 
Share this answer
 
v3
The BETWEEN[^] operator is equivalent to:
SQL
SomeDateColumn >= @frdate AND SomeDateColumn <= @todate

Therefore, it's obvious that the upper-bound (@todate) must ALWAYS be greater than or equal to the lower-bound (@frdate).

If the upper-bound is less than the lower-bound, then there is no value for which the condition be true.

For hard-coded bounds, it's simple enough to put them in the correct order. If the bounds are supplied by the user, and your UI is not capable of validating that the upper-bound is greater than or equal to the lower-bound, then you'll need to swap the values in SQL:
SQL
declare @frdate datetime, @todate datetime;
select @frdate='2016-04-01', @todate ='2015-12-01';

If @frdate > @todate 
BEGIN
    DECLARE @temp datetime;
    SELECT @temp = @frdate, @frdate = @todate, @todate = @temp;
END;

select billdate from test where SomeDateColumn between @frdate and @todate order by billdate asc;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900