SQL:Cast在SubString中不起作用

时间:2018-02-27 17:23:26

标签: sql sql-server substring

我们有一个字符串字段表示出生日期,现在我们必须将其转换才能执行所需的计算。但是,当我们使用CAST或CONVERT进行转换以执行计算时,它无法正常工作。

select distinct(ptr.RecordID)
from dbo.PatientRecord as ptr
where
ptr.CHName like 'Access2Loc%'
AND ptr.RecordID
in(
    select
         (
            case when 
                    (DATEDIFF(hour, convert(date,DOB,110), GETDATE())/8766)>18 
                then PatientID
                else NULL
                end
          ) as RecordID 
    from 
    PatientView
    where ISDATE(DOB) = 1
 )

2 个答案:

答案 0 :(得分:0)

SQL Server认为这是一个“功能”。这很难解释,但在where之前select不一定执行

在SQL Server 2012+中,使用try_convert()(或try_cast()

where ptr.CHName like 'Access2Loc%' and
      ptr.RecordID in (select (case when DATEDIFF(hour, try_convert(date, DOB, 110), GETDATE()) / 8766 > 18 
                                    then PatientID
                               end) as RecordID 
                       from PatientView
                       where ISDATE(DOB) = 1
                      )

在更古老的版本中,您可以使用case表达式获得相同的效果。

答案 1 :(得分:0)

- 这将保证## t1仅包含有效的dob行

{{1}}