Reputation: 7529
I have created a query which gets results between 2 dates, Its working fine..
Now i have a scenario in which users does not enter any date..In this case
I need to fetch all the result from database regardless of date..
The following query fails when user does not enter any date, it returns
empty result set.
Kindly guide me how to resolve this problem.
select * from emp_register
where date between ' 2015-03-26 15:42:52' and ' 2015-03-26 15:42:52'
or status= 'Y'
Date Format is Timestamp
Upvotes: 2
Views: 1076
Reputation: 49082
where date between ' 2015-03-26 15:42:52' and ' 2015-03-26 15:42:52'
' 2015-03-26 15:42:52'
is NOT a DATE, it is a string. Never ever rely on implicit data type conversion. You might just be lucky to get the result depending on your NLS settings, however, it will certainly fail when the client NLS settings will be different for others.
Now i have a scenario in which users does not enter any date..In this case I need to fetch all the result from database regardless of date
No need to do in PL/SQL, do it in SQL.
Use NVL function on the values. Use a default lower bound and upper bound date values in the BETWEEN clause for the NVL.
For example,
SELECT *
FROM emp_register
WHERE DATE BETWEEN NVL(:date1, DATE '1900-01-01') AND NVL(:date2, DATE '9999-01-01')
OR status= 'Y'
So, whenever :date1
and/or :date2
and/is NULL, then it would use the default date values to fetch all the rows from the table.
Upvotes: 2
Reputation: 14077
There are couple of options:
1900-01-01
and 2300-01-01
if user didn't pass any.Upvotes: 1