我有一个用例,我需要在where子句中编写一个包含case语句的查询,条件如下: 我在“ SAMPLE_TABLE”中有名为“ BIRTHDATE”的列 1)如果仅给出日期(这是一个参数,即:from),那么我需要从SAMPLE_TABLE获取记录,该记录的BIRTHDATE> =:from 2)如果仅给出日期(这是一个参数,即:to),则获取BIRTHDATE <=:to的记录 3)如果同时给出了起始日期和截止日期,则获取这些日期之间的记录。
下面是我尝试过的查询。但是无法解决。
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)
请提供一个有效的查询。预先感谢。
答案 0 :(得分:1)
如果不包括日期,则此代码将保留空白。这已经在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
或者您可以尝试
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)
答案 1 :(得分:0)
我想你只是想要
SELECT BIRTHDATE
FROM SAMPLE_TABLE
WHERE (BIRTHDATE >= :from OR :from IS NULL) AND
(BIRTHDATE <= :to OR :to IS NULL)
答案 2 :(得分:0)
我假设如果不传递某些参数,那么它的值为NULL。
where birthdate between coalesce(:from, date('0001-01-01')) and coalesce(:to, date('9999-12-31'))