2014-06-11 173 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個值是無效的,謝謝你提醒我檢查(我應該已經完成​​的)。 –