将空字符串转换为datetime

时间:2014-06-11 14:23:17

标签: sql tsql sql-server-2012

我在SQL Server数据库中有一个字符串类型的字段。该字段用于不同客户的不同事物。我们在这个字段中为一个客户存储日期。当字段未加载任何内容时,它为空(空字符串)。我需要从这个字段中为这个客户端提取数据,并在我的where语句中使用它。我认为将值转换为date数据类型是一件简单的事情,但我得到了错误

'从字符串转换日期和/或时间时转换失败。

以下是代码片段:where boldet.detmisc1 >= @begin 我尝试过以下方法:

where cast(boldet.detmisc1 as date) >= @begin

where cast(isnull(nullif(boldet.detmisc1, ''), ‘’) as date) >= @begin

有没有办法将空字符串值转换为空日期时间值,以便我可以在where语句中使用它?

数据库:SQL Server 2012

如果其他原因造成错误,我会附加整个查询:

    declare @begin datetime
set @begin = dateadd(dd, datediff(dd, 0, GETDATE()) - 1, 0)
declare @stop datetime
set @stop = dateadd(dd, datediff(dd, 0, GETDATE()), 0)
;
 with a as (select boldet.BOL_Key
 --boldet.DetMisc1

from ProBillTBL pro WITH (NOLOCK)
    INNER JOIN BOLTBL bol WITH (NOLOCK) On Pro.ProBill_Key = Bol.ProBill_Key
    INNER JOIN BOLDetailTBL boldet WITH (NOLOCK) On Bol.BOL_Key = BolDet.BOL_Key
    INNER JOIN ClientLocTBL cliloc WITH (NOLOCK) On Pro.ClientLoc_Key = Cliloc.ClientLoc_Key
    INNER JOIN CarrierTBL car WITH (NOLOCK) On Pro.Carrier_Key = Car.Carrier_Key
    --left outer join support sup (nolock) on pro.probill_key = sup.probill_key     

where cliloc.ClientLoc_Key = 2519
    and boldet.DetMisc3 in ('1', '4', '5')
     and (pro.ProEnteredDate >= @begin)

     or (cast((case when boldet.detmisc1 = '' then NULL else boldet.detmisc1 end) as date) >= @begin))


select * from a

当我评论此部分(cast((case when boldet.detmisc1 = '' then NULL else boldet.detmisc1 end) as date) >= @begin)时,我得到了一个结果,但是在where子句中我得到了错误。

1 个答案:

答案 0 :(得分:2)

试试这个:

WHERE 
  CAST((CASE WHEN boldet.detmisc1 = '' THEN NULL ELSE boldet.detmisc1 END) 
  As Date) >= @begin