2017-08-30 52 views
1

我有一個日期時間列,我正在檢查null。我想要做的就是讓它說「沒有下一個約會」,如果該列爲空。然而我得到一個錯誤:SQL - 從字符串中轉換日期和/或時間時出錯

conversion failed when converting date and/or time from character string

我不知道爲什麼。我嘗試了幾種不同的方式來編寫查詢,但它一直給我提供相同的錯誤。

這裏是我的query

SELECT 
t1.PatientID, 
t1.FullName, 
t1.CurrentRAF_DW, 
t1.NumberOfCompletedClinicVisits, 
t1.PreferredServiceLocation, 
case when t1.IsVip = 1 then 'Yes' else 'No' end as [IsVip], 
case when t1.PatientTier = 'Critical' then 'Every Three Weeks' 
    when t1.PatientTier = 'Serious' then 'Every 1 Month' 
    when t1.PatientTier = 'Fair' then 'Every 2 Months' 
    when t1.PatientTier = 'Good' then 'Every 3 Months' 
else ' '  
end as [Cadence], 
t1.PatientTier, 
t2.hcc_18, 
t2.hcc_19, 
t2.hcc_21, 
t2.hcc_22, 
t2.hcc_12, 
t2.hcc_136, 
t2.hcc_137, 
t2.hcc_108, 
t2.hcc_88, 
t2.hcc_111, 
t2.hcc_85, 
t2.hcc_55, 
t1.LastCompletedClinicVisit, 
case when t1.NextScheduledClinicVisit is not null then t1.NextScheduledClinicVisit else 'No Next Appointment' end as [NextScheduledVisit] 
FROM vw_patient_attributes t1 
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2 
    ON t1.PatientID = t2.emr_id 

在這裏討論的列是 「NextScheduledClinicVisit」。

+1

列'[NextScheduledVisit]'不能是兩種數據類型。將t1.NextScheduledClinicVisit轉換爲varchar,以便它和您的文本'No Next Appointment'都是varchar數據。類似於'CONVERT(VARCHAR(50),t1.NextScheduledClincVisit,101)'而不是 – xQbert

+0

'當t1.NextScheduledClinicVisit不爲空然後強制轉換(t1.NextScheduledClinicVisit as varchar(40))else'No Next Appointment'end as [NextScheduledVisit ]' – Hackerman

回答

5

首先,您應該使用coalesce()。其次,類型應符合:

coalesce(convert(varchar(255), t1.NextScheduledClinicVisit), 
     'No Next Appointment' 
     ) as [NextScheduledVisit] 

如果NextScheduledClinicVisit是刺痛,那麼你可能需要使用適當的轉換規範(如121),或者使用format()

+0

這是一個日期時間。這工作。謝啦!我試圖把這個標記爲「回答」,但它說我可以在8分鐘內做到這一點哈哈 –

2

該列有時會包含日期時間字段,有時還包含字符串。

嘗試將日期時間轉換爲varchar。

0

我會用下面的方法解決你的問題。

  1. 裹在try_convert錯誤發生柱和審查一些樣本記錄
  2. 如果上面寫成功使用類型「時,[COL]爲null,則‘格式文本1’...的情況下」你的case語句聲明並回顧一些樣本記錄

顯然戈登的回答是工作,所以使用,但我可能會考慮try_Convert以供將來參考。

相關問題