2014-06-11 164 views
0

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

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

以下是代码段:where boldet.detmisc1 >= @begin
我曾尝试以下:

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

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

有没有办法为空字符串值转换为空datetime值,这样我可以在我的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子句中,我得到错误。

回答

2

试试这个:

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

我仍然得到同样的错误。我编辑了我的帖子以包含整个查询。 –

+2

也许它不只是空字符串,而是其他无效的日期值。 – Magnus

+0

Magnus,我的第一反应是'不,这可能不是它。“但是,我确实检查并发现该字段中有2个值是无效的,谢谢你提醒我检查(我应该已经完成​​的)。 –