【问题标题】:SQL Check for Null Date and then Case SwitchSQL 检查空日期,然后进行大小写切换
【发布时间】:2012-02-21 21:56:53
【问题描述】:

我有一个要按两个不同日期过滤的数据结果。

除了completion_date 为空时,以下内容正常工作。如果它为 null,我想使用另一个名为 created_date 的字段。

string strSQL = string.Format(@"select * from my_table 

            where user_Id = {0}

            AND [completion_date] between {1} AND {2}

            order by completion_status  desc, [completion_date] asc"
            , userId, dateStart, dateEnd, visibilityIndicator);

大概是这样的:

string strSQL = string.Format(@"select * from my_table                                                   
where user_Id = {0}


CASE completion_date 
     WHEN is null THEN [completion_date] between {1} AND {2}
     ELSE [created_date] between {1} AND {2}

END 

AND                       
            order by completion_status  desc, [completion_date] asc"
            , userId, dateStart, dateEnd, visibilityIndicator);

检查该空值然后切换到 created_date 的最佳方法是什么?

【问题讨论】:

    标签: sql switch-statement case


    【解决方案1】:
    where isnull(completetion_date,created_date) between {1} and {2}
    

    应该工作

    【讨论】:

      【解决方案2】:
      string strSQL = string.Format(@"select * from my_table 
      where user_Id = {0}
      AND ISNULL([completion_date],[created_date]) between {1} AND {2}
       order by completion_status  desc, [completion_date] asc"
      

      【讨论】:

        【解决方案3】:

        ANSI SQL 兼容版本:

        SELECT * FROM my_table WHERE user_Id = {0}
        AND [completion_date] BETWEEN {1} AND {2}
        OR ([completion_date] IS NULL AND [created_date] BETWEEN {1} AND {2})
        ORDER BY completion_status DESC, [completion_date] ASC
        

        【讨论】:

        • 还有 ANSI COALESCE 但不确定它是否适用于此...也许吧。
        • 谢谢!一个有趣的解决方案。如果可能,我会尽量避免 Coalesce,这只是个人喜好。
        猜你喜欢
        • 2015-06-22
        • 1970-01-01
        • 2016-10-18
        • 2015-08-22
        • 1970-01-01
        • 1970-01-01
        • 2017-11-05
        • 2011-11-21
        • 2013-08-01
        相关资源
        最近更新 更多