SQL - 从字符串转换日期和/或时间时出错

标签 sql sql-server database

我有一个日期时间列,我正在检查它是否为空。如果该列为空,我只想让它说“没有下一次约会”。但是我收到一个错误:

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

我不确定为什么。我尝试了几种不同的方法来编写查询,但它一直给我同样的错误。

这是我的查询-

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”。

最佳答案

首先,您应该使用coalesce()。其次,类型应该匹配:

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

如果 NextScheduledClinicVisit 是一个 sting,那么您可能想要使用适当的转换规范(例如 121)或使用 format()

关于SQL - 从字符串转换日期和/或时间时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45969050/

相关文章:

sql - 为什么这个 MySQL 更新会永远持续?

mysql - 查找哪个表有该列数据

mysql - 如何使用sql获取满足一定条件的结果?

sql - 根据具有名称列名称的另一个表更新表中 100 列行的 SQL

sql-server - 为什么 t-SQL 按日期时间排序在 SQL SMS 中正确,但在 ASP Classic 输出中不正确?

mysql - 数据库索引困惑

javascript - 给每个 CouchDB 用户一个单独的数据库是好的做法吗?

c# - 如何在 Entity Framework 中使用 String 属性作为主键

sql - 获取表sql中每个字段的名称

c# - 将SQL查询结果数据提前加载到缓存中