另一種選擇是使用substring
和patindex
和一些公共表表達式來獲得期望的結果:
首先,創建並填充示例表格:(請拯救我們在你未來的問題,這一步)
DECLARE @T AS TABLE
(
Duration varchar(40),
NumberOfSeconds int
)
INSERT INTO @T (Duration) VALUES
('39 Seconds'),
('2 Minutes 4 Seconds'),
('1 Hours 7 Minutes 17 Seconds'),
('3 Days 9 Hour 8 Minutes 25 Seconds')
然後,使用一個CTE來保存patindex
結果每個字。
這個cte只是爲了節省我們一次又一次地寫patindex
的必要。 另一個CTE加入這一條,將使用substring
提取值爲每個時間部分,採用第一CTE:
;WITH cte1 as
(
SELECT *,
PATINDEX('%Day%', Duration) As DaysIndex,
PATINDEX('%Hour%', Duration) As HoursIndex,
PATINDEX('%Minute%', Duration) As MinutesIndex,
PATINDEX('%Second%', Duration) As SecondIndex
FROM @T
), cte2 as
(
SELECT *,
CASE WHEN DaysIndex > 0 THEN
CAST(SUBSTRING(Duration, 0, DaysIndex) As int) * 60 * 60 * 24
ELSE
0
END As D,
CASE WHEN HoursIndex > 0 THEN
CAST(
SUBSTRING(Duration,
CASE WHEN DaysIndex > 0 THEN DaysIndex + 4
ELSE 0
END,
CASE WHEN DaysIndex > 0 THEN HoursIndex - DaysIndex - 4
ELSE HoursIndex
END
) As int) * 60 * 60
ELSE
0
END As H,
CASE WHEN MinutesIndex > 0 THEN
CAST(
SUBSTRING(Duration,
CASE WHEN HoursIndex > 0 THEN HoursIndex + 5
ELSE 0
END,
CASE WHEN HoursIndex > 0 THEN MinutesIndex - HoursIndex - 5
ELSE MinutesIndex
END
) As int) * 60
ELSE
0
END As M,
CASE WHEN SecondIndex > 0 THEN
CAST(
SUBSTRING(Duration,
CASE WHEN MinutesIndex > 0 THEN MinutesIndex + 7
ELSE 0
END,
CASE WHEN MinutesIndex > 0 THEN SecondIndex - MinutesIndex - 7
ELSE SecondIndex
END
) As int)
ELSE
0
END As S
FROM cte1
)
現在,更新NumberOfSeconds
柱:
UPDATE cte2
SET NumberOfSeconds = D + H + M + S
驗證更新結果:
SELECT *
FROM @T
結果:
Duration NumberOfSeconds
---------------------------------------- ---------------
39 Seconds 39
2 Minutes 4 Seconds 124
1 Hours 7 Minutes 17 Seconds 4037
3 Days 9 Hour 8 Minutes 25 Seconds 292105
應該可以使用字符串函數來實現你想要的。但是,爲什麼要避免這種痛苦呢?將時間戳存儲爲...時間戳而不是'nvarchar'。 –
@TimBiegeleisen - 我同意你的觀點,但我不是這個數據庫的管理員,並且嚴格來說是數據的使用者。 – Zachafer
如果只有2分鐘,該怎麼辦?它說0天0小時2分鐘嗎? – scsimon