简体   繁体   中英

SQL Server Date Column Inconsistent

I have column date with string(nvarchar) format. and I have inconsistent column like this

不一致的日期列

I have more example like this

2021-7-01
2021-8-01

first I have try with CASE WHEN like this

SELECT 
    CASE 
    WHEN DATE_IN LIKE '[0-9]{4}-[0-9]{2}-[0-9]{2}'
                    THEN CONVERT(datetime, date_in, 102)
                    WHEN date_in LIKE '[0-9]{4}-[0-9]{2}-[0-9]{2}'
                    THEN CONVERT(datetime, date_in) END AS DATE_IN, EMP_NAME,DATE_IN
FROM staging.irisEtcSingleFile

but, the output is NULL.. I want the output is like this

2021-01-01
2021-07-01
2021-08-01

I really appreciate to get the answer.. Thanks before

Try this snippets, produces a good response:

create table #t (txt varchar(100))
delete from #t
go

insert into #t select '2021-7-01'
insert into #t select '2021-8-01'
insert into #t select '2021-01-01'
insert into #t select '2021-07-01'
insert into #t select '2021-2-02'
insert into #t select '2021-08-01'

go

select 
    txt
from 
    #t
where
    txt not like '%[^0-9-]%' and
    len(replace(txt, '-', '')) = len(txt)-2 and
    txt like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'

Output:

2021-01-01
2021-07-01
2021-08-01

Check this query using

replicate

SELECT 
    CASE 
    WHEN test_col LIKE REPLICATE('[0-9]',4) + '-[0-9]-' + REPLICATE('[0-9]',2)
                    THEN CONVERT(datetime, test_col, 102)
                    WHEN test_col LIKE REPLICATE('[0-9]',4) + '-' + REPLICATE('[0-9]',2) + '-' + REPLICATE('[0-9]',2)
                    THEN CONVERT(datetime, test_col) END AS test_col
FROM test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM