从 varchar 到没有日期的时间的时间转换问题

Time conversion issue from varchar to time without date

此查询按预期工作

SELECT CAST('8:40 AM' AS TIME) Times
UNION
SELECT CAST('12:01 PM' AS TIME)
UNION
SELECT CAST('12:04 PM' AS TIME)
UNION
SELECT CAST('12:41 PM' AS TIME)
UNION
SELECT CAST('12:45 PM' AS TIME)
UNION
SELECT CAST('1:28 PM' AS TIME)
UNION
SELECT CAST('1:43 PM' AS TIME)

以上SELECT查询的输出

Times
----------------
08:40:00.0000000
12:01:00.0000000
12:04:00.0000000
12:41:00.0000000
12:45:00.0000000
13:28:00.0000000
13:43:00.0000000

此查询也按预期工作

DECLARE @timeString VARCHAR(MAX) =
'
8:40 AM ,
12:01 PM,
12:04 PM,
12:41 PM,
12:45 PM,
1:28 PM ,
1:43 PM,,
'

;WITH CTE AS
(
    SELECT TIMELIST.a.value('.','VARCHAR(MAX)') Times FROM(SELECT CAST('<P>'+REPLACE(@timeString,',','</P><P>')+'</P>' AS XML) AS TIMESPLIT) AS T CROSS APPLY  T.TIMESPLIT.nodes('/P') AS TIMELIST(a)
)
SELECT LTRIM(RTRIM(Times)) Times FROM CTE WHERE Times != ''

以上SELECT查询的输出

Times
------------
8:40 AM
12:01 PM
12:04 PM
12:41 PM
12:45 PM
1:28 PM
1:43 PM

此查询未按预期工作

;WITH CTE AS
(
    SELECT TIMELIST.a.value('.','VARCHAR(MAX)') Times FROM(SELECT CAST('<P>'+REPLACE(@timeString,',','</P><P>')+'</P>' AS XML) AS TIMESPLIT) AS T CROSS APPLY  T.TIMESPLIT.nodes('/P') AS TIMELIST(a)
)
SELECT CAST(LTRIM(RTRIM(Times)) AS TIME) Times FROM CTE WHERE Times != ''

以上查询returns错误。

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

"string" 值包含换行符(CR 和 LF)。 LTRIM/RTRIM 不要 trim 这些字符,所以你需要:

WITH CTE AS
(
    SELECT TIMELIST.a.value('.','VARCHAR(MAX)') Times
    FROM (
         SELECT CAST('<P>'+REPLACE(@timeString,',','</P><P>')+'</P>' AS XML) AS TIMESPLIT
    ) AS T
    CROSS APPLY T.TIMESPLIT.nodes('/P') AS TIMELIST(a)
)
SELECT CAST(REPLACE(REPLACE(LTRIM(RTRIM(TIMES)), CHAR(10), ''), CHAR(13), '') AS VARCHAR) Times
FROM CTE WHERE Times!=''

如果您使用的是 SQL 2016+,那么 STRING_SPLIT 是一个更优雅的解决方案。如果您使用的是 2017+,那么 TRIM(... FROM ...) 会简化 trimming.