我需要從看起來像這樣的文本欄位中提取日期/時間到日期/時間列中:
一些文字 - 2021 年 7 月 29 日 16:44
一些不同的文字 - 2021 年 7 月 2 日 12:31
重現的示例代碼:
select 'some text - 29th Jul 2021 16:44'
union
select
'some different text - 2nd Jul 2021 12:31'
as textfield
這是我正在查詢的供應商提供的資料庫 - 無法更改格式。
我需要將日期和時間提取到日期時間欄位中(目的是與不同的日期時間欄位進行比較)。
這樣做有什么“捷徑”嗎?我已經開始嘗試許多手動子字串函式來提取各個部分以再次拼湊起來,但它非常麻煩,我覺得必須有更好的方法。
破折號 (-) 總是會在相同的位置(相對于日期方面),這很有幫助,但我仍然覺得我走錯了路。
有沒有辦法可以在破折號后添加子字串,并讓 SQL Server 識別格式?
這里的一個挑戰是 1-9 的“天”方面將是個位數,而 10-31 則是兩位數。
uj5u.com熱心網友回復:
對于您的示例資料,您可以使用replace和 a來完成此操作substring:
with t as (
select 'some text - 29th Jul 2021 16:44' as textfield
union
select
'some different text - 2nd Jul 2021 12:31'
)
select Try_parse(y.d as datetime using 'en-GB') as ExtractedDate
from t
cross apply(values(Substring(t.textfield, CharIndex('-',t.textfield) 2 ,100)))x(v)
cross apply(values(Replace(Replace(Replace(Replace(x.v,'st',''),'nd',''),'rd',''),'th','')))y(d)
uj5u.com熱心網友回復:
如果你喜歡簡潔:
convert(datetime, stuff(right(txt, 19), 3, 2, ''), 106)
https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=c8720885ef6239187b2c220d0dfa9ae2
This conversion relies on there being a space following the hyphen so that when picking up the rightmost 19 characters you'll either end up with a digit or a space character in the initial position. 然后,這允許您從已知位置去除序數文本的兩個字符。(我最初ltrim()在轉換之前輸入了一個,但可能的前導空格似乎并沒有破壞轉換。)
一個優點是避免了在文本的前導部分有其他連字符干擾搜索的可能性。完全消除了標記/分隔符的整個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358142.html
標籤:sql sql-server
上一篇:從Python中的SQL陳述句字串中獲取INSERTINTO陳述句
下一篇:Sqlsum值不同的id
