![](/img/trans.png)
[英]DB2 SQL Statement WHERE clause CASE WHEN in multiple conditions
[英]case inside where clause which contains where conditions in db2
我有一个用例,我需要在 where 子句中编写一个包含 case 语句的查询,条件如下:我在 'SAMPLE_TABLE' 中有一列名为 'BIRTHDATE' 1) if only from date (which is a param ie, :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)
请提供一个有效的查询。 提前致谢。
此代码可以,当不包含日期时将其留空。 这是在 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)
我想你只是想要:
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'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.