SQL Server 从字符串中提取年份

vsaztqbk  于 2023-01-20  发布在  其他
关注(0)|答案(3)|浏览(125)

是否可以从随机字符串中提取年份?例如“randomtext20221108randomtext”
在它之前或之后的文本从来都不一样,但日期格式“20221108”是一样的。

nxagd54h

nxagd54h1#

我想这个查询可能会对您有所帮助,

DECLARE @yourText varchar(100) = 'randomtext20221108randomtext'
DECLARE @begin int = PATINDEX('%[0-9][0-9][0-9][0-9]%', @yourText)
DECLARE @end int = @begin + 7

SELECT SUBSTRING(@yourText, @begin, @end - @begin + 1)

如果你只需要一年,你可以

SELECT SUBSTRING('randomtext20221108randomtext', PATINDEX('%[0-9][0-9][0-9][0-9]%', 'randomtext20221108randomtext') , 4)
polhcujo

polhcujo2#

下面的例子可能对您有用,假设日期都是本世纪

select s, Substring(s, p, 4) [Year]
from (
  values('kdfjgkj44kjf420221108dfkgjhdfiuh45rt'),('qwerty20210409'),('nodate 2345 here')
)t(s)
cross apply(values(NullIf(PatIndex('%2[0-9][0-9][0-9][0-9][1-9][0-9][1-9]%', s),0)))p(p);
knsnq2tg

knsnq2tg3#

create table #randomTexts (col1 nvarchar(max));

insert into #randomTexts values ('randomtext20221108randomtext');
insert into #randomTexts values ('2022asdasd20211108randomtext');
insert into #randomTexts values ('1234567820181108randomtext');
insert into #randomTexts values ('xxx20331332zzz20221108randomtext');

WITH CTE_Numbers AS 
(
    SELECT MAX(LEN(col1))-1 as n FROM #randomTexts
    UNION ALL 
    SELECT n-1 FROM CTE_Numbers
    WHERE n>0
)
SELECT col1,CAST(SUBSTRING(col1,n,8) AS DATE) AS validDate, SUBSTRING(col1,n,4) AS year
FROM #randomTexts
CROSS JOIN CTE_Numbers
WHERE TRY_CAST(SUBSTRING(col1,n,8) AS DATE) IS NOT NULL
AND n+8<= LEN(col1);

相关问题