条款发布的情况

时间:2014-10-02 14:50:19

标签: sql case where

我试图写一个WHERE子句,为一个实例捕获一组参数,为另一个实例捕获另一个参数。

现在我写了这样的话:

Where 
    s.ProjectID=110 
    and wfseg.SiteEventGroupID=3 
    and wfse.EventStatusID in (1,2)
    CASE WHEN cf.PaperDocumentTypeID <> 1 
      THEN CAST(cf.DateUploaded as DATE) = '09/25/2014'  
      ELSE CAST(cf.DateUploaded as DATE) = '09/25/2014' AND CAST(cr.CheckDate as DATE) ='09/25/2014'  
    END

如果PaperDocumentType不是1,那么它应该显示参数CAST(cf.DateUploaded as DATE) = '09/25/2014'如果文档是1,那么它应该显示以下两个参数CAST(cf.DateUploaded as DATE) = '09/25/2014' AND CAST(cr.CheckDate as DATE) ='09/25/2014'

所以我在运行之前遇到错误 - 不确定我应该如何重写以使其正常运行。

4 个答案:

答案 0 :(得分:3)

它是CASE WHEN,而不是CASE WHERE

答案 1 :(得分:2)

试一试

Where 
    s.ProjectID = 110  and 
    wfseg.SiteEventGroupID = 3 and 
    wfse.EventStatusID in (1,2) and

   CAST(cf.DateUploaded as DATE) = @parameter and
   CAST(cr.CheckDate as DATE) = (case when whencf.PaperDocumentTypeID <> 1  then @parameter else CAST(cr.CheckDate as DATE)END)

答案 2 :(得分:1)

首先,它将基于CASE WHEN,而不是CASE WHERE。此外,对CAST()日期的查询到完整日期时间的日期将阻止任何此类索引被优化为具有日期字段。

为了简化你的case子句,因为cast()是相同的日期,它可以缩短为

 s.ProjectID=110 
    and wfseg.SiteEventGroupID=3 
    and wfse.EventStatusID in (1,2)
    and CAST(cf.DateUploaded as DATE) = '09/25/2014'
    and (    cf.PaperDocumentTypeID = 1 
        OR ( cf.PaperDocumentTypeID <> 1  and CAST(cr.CheckDate as DATE) ='09/25/2014' ))

如果不进行施法,你可以做......

    and cf.DateUploaded >= '2014-09-25' and cf.DateUploaded < '2014-09-26'

这样,它可以在9/25到下午11:59:59之间得到所有时间。稍长一点,但如果日期是索引的一部分则更好。

答案 3 :(得分:1)

案件的格式没有单词&#39; WHERE&#39;。 (Link To MySQL Doc

CASE  cf.PaperDocumentTypeID <> 1
THEN  CAST(cf.DateUploaded as DATE) = '09/25/2014'  
ELSE  CAST(cf.DateUploaded as DATE) = '09/25/2014' AND CAST(cr.CheckDate as DATE) ='09/25/2014'
END

你也可以使用&#39; WHEN&#39;条款使结构更像是一个C&#39;像这样切换:

CASE cf.PaperDocumentTypeID
WHEN 1 THEN CAST(cf.DateUploaded as DATE) = '09/25/2014' AND CAST(cr.CheckDate as DATE) ='09/25/2014'
WHEN 2 THEN  . . . 
WHEN 3 THEN  . . . 
ELSE CAST(cf.DateUploaded as DATE) = '09/25/2014'  
END

其次,我认为MySQL日期的格式为“YYYY-MM-DD”,但它可能是特定于本地化的,所以我并非100%肯定。另外,不要忘记另一种生成日期的方法是来自 DATE()函数。我不确定哪个更有效CASE()或DATE()。
示例:

DATE(cf.DateUploaded) = '2014-09-25'