隨便你用哪個SQL@@~我是使用MSSQL
這次應該就沒有字元長度問題了~應該比較簡單點^^"
declare @Tmp table(
StrTmp nvarchar(100)
)
insert into @Tmp
values(N'你知道嗎?中秋節是2021/09/21(二),但2021/09/20(一)也是放假日唷')
,(N'2021年最後一個假期2021/10/11(一)嗎?還是2021/12/31(五)呢?')
,(N'雙十節日2021/10/10(日)剛好在星期日呢')
這次大家都動作滿快查詢出來~
晚點再貼我的查詢方式@@"
以下我用取10個字元比對是否為日期,再列出來~
select SUBSTRING(StrTmp,Sort,10) ShowDate
from @Tmp
,(
select Row_Number()Over(order by [number]) as Sort
from master..spt_values
) as k
where Sort <= len(StrTmp)
and isDate(SUBSTRING(StrTmp,Sort,10)) = 1
order by SUBSTRING(StrTmp,Sort,10)
DECLARE @result table (ShowDate varchar(10))
DECLARE @tmpstr varchar(200)
DECLARE @pos int
DECLARE myCURSOR CURSOR FOR
SELECT StrTmp from @Tmp
OPEN myCURSOR
FETCH NEXT FROM myCURSOR INTO @tmpstr
WHILE @@FETCH_STATUS = 0
BEGIN
set @pos=1
while @pos>0
begin
select @pos=PATINDEX('%[0-9][0-9][0-9][0-9]/%',@tmpstr)
if (@pos>0)
begin
insert into @result
select substring(@tmpstr,@pos,10)
set @tmpstr=substring(@tmpstr,@pos+10,len(@tmpstr)-10)
end
end
FETCH NEXT FROM myCURSOR INTO @tmpstr
END
CLOSE myCURSOR
DEALLOCATE myCURSOR
select ShowDate from @result
order by ShowDate
CREATE TABLE Tmp (
StrTmp nvarchar(100));
INSERT INTO Tmp
values(N'你知道嗎?中秋節是2021/09/21(二),但2021/09/20(一)也是放假日唷')
,(N'2021年最後一個假期2021/10/11(一)嗎?還是2021/12/31(五)呢?')
,(N'雙十節日2021/10/10(日)剛好在星期日呢');
WITH CTE_X1 AS (
SELECT StrTmp,
SUBSTRING(StrTmp,CHARINDEX('(', StrTmp)-10,10) AS STRA,
SUBSTRING(StrTmp,CHARINDEX('(', StrTmp)+1,LEN(StrTmp)-CHARINDEX('(', StrTmp)) AS STRB,
CHARINDEX('(', StrTmp) AS NUM
FROM Tmp
UNION ALL
SELECT StrTmp,
SUBSTRING(STRB,CHARINDEX('(', STRB)-10,10) AS STRA,
SUBSTRING(STRB,CHARINDEX('(', STRB)+1,LEN(STRB)-CHARINDEX('(', STRB)) AS STRB,
NUM + 1 AS NUM
FROM CTE_X1
WHERE LEN(StrTmp) - NUM>0
)
SELECT STRA
FROM CTE_X1 AS A
WHERE STRA <>''
ORDER BY STRA
日期未必是10個字,
2021/09/21,20210921也是日期,
固定切10字元來判斷,不足啦。
create table it210703 (
txt text
);
insert into it210703 values
('你知道嗎?中秋節是2021/09/21(二),但2021/09/20(一)也是放假日唷')
,('2021年最後一個假期2021/10/11(一)嗎?還是2021/12/31(五)呢?')
,('雙十節日2021/10/10(日)剛好在星期日呢');
create or replace function is_date(s varchar)
returns boolean
language plpgsql as
$code$
begin
perform s::date;
return true;
exception when others then
return false;
end;
$code$;
with t1 (datetxt) as (
select unnest(regexp_matches(txt, '\d{4}.\d{2}.\d{2}', 'g'))
from it210703
)
select datetxt
, is_date(datetxt)
from t1;
datetxt | is_date
------------+---------
2021/09/21 | t
2021/09/20 | t
2021/10/11 | t
2021/12/31 | t
2021/10/10 | t
(5 rows)
這句regexp_matches真好~SQL Server沒有正規化取代函數Q_Qa
不過PostgreSQL沒有判斷字串is_date是否為日期@@...
is_date 這類的沒有內建,但是有一個很好用的 extension
https://github.com/sjstoelting/pgsql-tweaks
有很多方便的函數,有包含 is_date(), is_timestamp() 等等.