Reputation: 377
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?
Upvotes: 0
Views: 165
Reputation: 26460
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'
Upvotes: 3
Reputation: 144
Try with this.
SELECT
CONVERT(TIME,(LEFT(schedulename,8))) AS login,
CONVERT(TIME,(RIGHT(schedulename,8))) AS logout
FROM employeesschedulelist
WHERE employeeidno='D0150000005'
Upvotes: 2