I have use case where I need to write a query which contains case statement in where clause with conditions like below : I have column in 'SAMPLE_TABLE' called 'BIRTHDATE' 1) if only from date (which is a param ie, :from) is given, then I need to get the records from SAMPLE_TABLE whose BIRTHDATE >= :from 2) if only to date (which is a param ie, :to) is given,then get records whose BIRTHDATE <= :to 3) if both from and to dates are given, then get the records between those dates.
Below is the query I tried. But couldn't get the solution.
SELECT BIRTHDATE FROM SAMPLE_TABLE
WHERE
(CASE
WHEN (:from AND NOT :to)
THEN BIRTHDATE >= :receivefrom
WHEN (:to AND NOT :from)
THEN BIRTHDATE <= :to
WHEN (:to AND :from)
THEN BIRTHDATE BETWEEN :from AND :to
END)
Please provide a working query. Thanks in advance.
This code would do, when a date is not included leave it as blank. This was tested in SQL Server
declare @from date='1998-12-07'
declare @to date ='2000-12-07'
SELECT [Birthdate] --when only from is available
FROM SAMPLE_TABLE
where (case when (@to='' and @from !='') then 1 else 0 end)=1
and BIRTHDATE >= @from
UNION
SELECT [Birthdate] --when only to is available
FROM SAMPLE_TABLE
where (case when (@to!='' and @from ='') then 1 else 0 end)=1
and BIRTHDATE <= @to
UNION
SELECT [Birthdate] --when both from and to are avilable
FROM SAMPLE_TABLE
where (case when (@to!='' and @from !='') then 1 else 0 end)=1
and BIRTHDATE between @from and @to
Or else you can try this
declare @from date='1998-12-07'
declare @to date ='2000-12-07'
IF (@from!='' and @to!='')
SELECT [Birthdate]
FROM SAMPLE_TABLE
Where [Birthdate] between @from and @to
ELSE IF (@from='' and @to!='')
(SELECT [Birthdate]
FROM SAMPLE_TABLE
Where [Birthdate]<= @to)
ELSE IF (@from!='' and @to='')
(SELECT [Birthdate]
FROM SAMPLE_TABLE
Where [Birthdate]>= @from)
I think you simply want:
SELECT BIRTHDATE
FROM SAMPLE_TABLE
WHERE (BIRTHDATE >= :from OR :from IS NULL) AND
(BIRTHDATE <= :to OR :to IS NULL)
我假设如果不应该传递某个参数,那么它具有 NULL 值。
where birthdate between coalesce(:from, date('0001-01-01')) and coalesce(:to, date('9999-12-31'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.