I need to validate a column having time ranges like '8:00 am - 9:00 pm' I n开发者_如何转开发eed to split this column into two and update to my table with the date with current date but the time from the range for example "2011-05-23 08:00:00" And "2011-05-23 21:00:00" for the range record. kindly help. Also I need to process if the data is '8:00 a.m. - 9:00 p.m.', '8:00 a.m - 9:00 p.m' or '8:00 am - 12:00 noon'. If there is no "-" need to reject the data for the record.
Here's a basic solution, which, I think, could well be used as a starting point:
DECLARE @Today datetime = CAST(GETDATE() AS date);
WITH datasource (TimeRange) AS (
SELECT '10 a.m. - 1 p.m.' UNION ALL
SELECT '8 am - 12 noon' UNION ALL
SELECT '12 noon - 4 p.m.' UNION ALL
SELECT '9 - 10 am' UNION ALL
SELECT '10 am 1 pm'
),
HyphensIncluded AS (
SELECT *, HyphenPos = CHARINDEX('-', TimeRange)
FROM datasource
WHERE CHARINDEX('-', TimeRange) > 0
),
Split AS (
SELECT
*,
StartTimeStr = REPLACE(
REPLACE(
LTRIM(RTRIM(SUBSTRING(TimeRange, 0, HyphenPos))),
'.',
''
),
'noon',
'pm'
),
EndTimeStr = REPLACE(
REPLACE(
LTRIM(SUBSTRING(TimeRange, HyphenPos + 1, LEN(TimeRange) - HyphenPos)),
'.',
''
),
'noon',
'pm'
)
FROM HyphensIncluded
),
Validated AS (
SELECT *
FROM Split
WHERE ISDATE(StartTimeStr) = 1
AND ISDATE(EndTimeStr) = 1
)
SELECT
StartTimestamp = @Today + StartTimeStr,
EndTimestamp = @Today + EndTimeStr
FROM Validated
Output:
StartTimestamp EndTimestamp
----------------------- -----------------------
2011-05-23 10:00:00.000 2011-05-23 13:00:00.000
2011-05-23 08:00:00.000 2011-05-23 12:00:00.000
2011-05-23 12:00:00.000 2011-05-23 16:00:00.000
it can be implemented using a trigger. Use 24H time format to avoid dealing with AM/PM.
精彩评论