将char转换为日期时间的问题

时间:2016-06-09 13:39:07

标签: sql sql-server database

我写过以下代码&我试图在这个表中搜索特定时期之间的行:

SELECT 'RWH' + P.Hospital_Number AS MRN,
       P.Date_of_birth, 
       pd.Clinic_date AS Date_Seen,  
       pd.Clinic_type_No
FROM (Patient_diabetes AS pd 
INNER JOIN Patients AS p ON pd.Patient_No = p.Patient_No) 
INNER JOIN Staff AS s ON pd.Seen_by1_No = s.Staff_No
WHERE (((pd.Clinic_type_No)=241))
--AND hospital_number like '%63028%'
AND CONVERT(datetime,pd.Clinic_Date,121) BETWEEN '02/04/2015' AND '24/09/2015'
ORDER BY p.Date_of_birth,
pd.Clinic_date DESC

但我收到以下错误,有任何想法如何解决这个问题?:

  

Msg 242,Level 16,State 3,Line 2 char数据类型的转换   日期时间数据类型导致超出范围的日期时间值。

2 个答案:

答案 0 :(得分:1)

我认为问题出现在BETWEEN '02/04/2015' AND '24/09/2015'

默认情况下,'24/09/2015'会转换为"mm/dd/yyyy"格式数据。所以没有第24个月。

尝试明确指出字符串数据的格式:

BETWEEN CONVERT(datetime,'02/04/2015',103) 
    AND CONVERT(datetime,'24/09/2015',103)  

答案 1 :(得分:1)

我建议你改变:

AND CONVERT(datetime,pd.Clinic_Date,121) BETWEEN '02/04/2015' AND '24/09/2015'

对此:

AND CONVERT(date,pd.Clinic_Date,121) BETWEEN '2015-04-02' AND '2015-09-24'