代码之家  ›  专栏  ›  技术社区  ›  Sai

如何从SQL Server 2012中选择datetime where isnull值?

  •  1
  • Sai  · 技术社区  · 6 年前

    我有 tb_user_log 收集用户登录和注销历史记录,它有两个COL( timein timeout )但如果系统错误,则超时列为空值。

    我需要选择它并显示它 null 还是不行 无效的 .

    我有下面的代码,但只在值不为null时返回,并在超时为null时隐藏重新编码:

    select *    
    from tb_user_log 
    where cast(Logintime as date) >= '2018-05-16' 
      and (cast(Logouttime as date) <= '2018-05-16' or
           cast(logouttime as date) <= '') 
    order by id desc
    

    我的代码中有错误的地方吗?它不返回空的重新编码。

    或者有更好的选择方法吗?我的数据类型是 datetime 我使用的是C#+SQL Server 2012。

    非常感谢。

    1 回复  |  直到 6 年前
        1
  •  3
  •   S3S    6 年前

    你可以测试 Logouttime 反对 NULL :

    select *    
    from tb_user_log 
    where cast(Logintime as date) >= '2018-05-16' 
      and (cast(Logouttime as date) <= '2018-05-16' or logouttime is null) 
    order by id desc
    

    或者你可以处理 无效的 条件中的值:

    select *    
    from tb_user_log 
    where cast(Logintime as date) >= '2018-05-16' 
      and (cast(isnull(Logouttime,'') as date) <= '2018-05-16') 
    order by id desc
    

    在这两种情况下,在结果中,您还将获得具有 logouttime is null