简体   繁体   中英

MSSQL Server 2008 Conversion failed when converting date and/or time from character string Error

I am currently receiving the MSSQL Server 2008 error: Conversion failed when converting date and/or time from character string.

I've checked the following threads but am still having no lucks:

Conversion failed when converting date and/or time from character string while inserting datetime Conversion failed when converting date and/or time from character string in SQL SERVER 2008

Here is the query (I'm using PHP's PDO SQLSRV):

SELECT ISNULL(MYDATE,'None') AS MYDATE, 
ISNULL(CAST(rnm AS NVARCHAR(50)),'None') AS Rnm, 
DATENAME(dw, MYDATE) as nameOfDay, 
FROM tab1
INNER JOIN rnm ON (tab1.rte = rnm.rte)
WHERE DATEDIFF(S, '1970-01-01', MYDATE) >= :startDate
AND DATEDIFF(S, '1970-01-01', MYDATE) <= :endDate
GROUP BY MYDATE, CAST(rnm AS NVARCHAR(50)) WITH ROLLUP

The MYDATE field is of the type datetime in MSSQL. I have tried casting each of the MYDATE variables and the 1970-01-01 all as datetime, but I still receive the error.

The "rnm" is cast as VARCHAR because it's an old DB using the "text" type still, unfortunately.

Thanks.

---update:

$startDate = strtotime($_GET['startDate'] . " 00:00:00");
$endDate = strtotime($_GET['endDate'] . " 23:59:59");

The above is then bound to the prepared variable via bindParam() .

You are grouping by MYDATE which is datetime instead of IsNull(MYDATE, 'None') which is varchar and sometimes stores 'None' as a value. All those DATEDIFFs and conversions inside WHERE clause will lead to performance issues. Try to remove DATEDIFFs and pass startdate/enddate in datetime format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM