简体   繁体   中英

Conversion failed when converting date and/or time from character string when converting inputted time | SQL, SQLSRV

I have a problem with this query. I'm receiving the following error below.

What I'm trying to do is to convert the 10:00 PM to 22:00, basically from 12 hour format to 24 hour format.

Msg 241, Level 16, State 1, Line 2 Conversion failed when converting date and/or time from character string.

The value of the schedulename column is

10:00 PM - 06:00 AM

10:00 PM - 06:00 AM

and one row called REST

I set it to LEFT(schedulename,8) so that I can get the schedule on the left, and then RIGHT(schedulename,8) so that I can get the schedule on the right.

I'm using SQLSRV, SQLSERVER 2012, and XAMPP.

SELECT 
Format(cast(LEFT(schedulename,8) as datetime),'HH:mm:ss') AS login,
Format(cast(RIGHT(schedulename,8) as datetime),'HH:mm:ss') AS logout 
FROM
employeesschedulelist 
WHERE 
employeeidno='D0150000005'

I also tried this, but no luck.

SELECT 
CONVERT(VARCHAR, LEFT(schedulename,8), 108) as login,
 CONVERT(VARCHAR, RIGHT(schedulename,8), 108) as logout 
from employeesschedulelist 
where employeeidno='D0150000005'

Is there another solution to this without changing my column?

You can use TRY_CAST() instead of CAST() . If the conversion fails, it will return NULL .

SELECT FORMAT(TRY_CAST(LEFT(schedulename ,8) AS DATETIME),'HH:mm:ss') AS login,
       FORMAT(TRY_CAST(RIGHT(schedulename, 8) AS DATETIME),'HH:mm:ss') AS logout 
FROM employeesschedulelist 
WHERE employeeidno = 'D0150000005'

Try with this.

SELECT 
CONVERT(TIME,(LEFT(schedulename,8))) AS login,
CONVERT(TIME,(RIGHT(schedulename,8))) AS logout 
FROM employeesschedulelist 
WHERE employeeidno='D0150000005'

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