If you can get away with just using the date for your diff, that's going to be a lot easier. You can readily convert YYYYMMDD to a date
value using convert(date, '20231109', 112)
.
If you need the time precision, you're going to have to do some string manipulation like you have. To use it in a where clause, you just say where {your_converting_expression_here} > dateadd(month, -1, getdate())
select *
from yourTable
where CONVERT(datetime,
(
LEFT(ABCD,4) + SUBSTRING(ABCD,5,2) + SUBSTRING(ABCD,7,2)
+ ' '
+ SUBSTRING(ABCD,9,2) + ':'+ SUBSTRING(ABCD,11,2) + ':'+ SUBSTRING(ABCD,13,2)),
101) > dateadd(month, -1, getdate()
If you don't want all that gobbldygook in your query, you can abstract the logic into a function like this:
create or alter function dbo.ParseUglyString
(
@UglyString varchar(16)
)
returns table
as
return
with a as
(
select
Yr = substring(@UglyString, 1, 4),
Mon = substring(@UglyString, 5, 2),
D = substring(@UglyString, 7, 2),
H = substring(@UglyString, 9, 2),
M = substring(@UglyString, 11, 2),
S = substring(@UglyString, 13, 2)
)
select
a.Yr,
a.Mon,
a.D,
a.H,
a.M,
a.S,
b.ReconstructedDate
from a
cross apply
(
select ReconstructedDate = datetimefromparts(Yr, Mon, D, H, M, S, 0)
) b
To call it, do:
drop table if exists #SomeData
select
Dt,
DtStr,
StringVal = MDY + H + M + S + 'CD'
into #SomeData
from sys.all_objects a
cross apply (select Dt = dateadd(day, checksum(newid()) % 60, getdate())) b
cross apply (select DtStr = convert(varchar(30), Dt, 120)) c
cross apply
(
select
MDY = convert(char(8), Dt, 112),
H = substring(DtStr, 12, 2),
M = substring(DtStr, 15, 2),
S = substring(DtStr, 18, 2)
) d
select *
from #SomeData a
cross apply dbo.ParseUglyString(a.StringVal) b
where b.ReconstructedDate > dateadd(month, -1, getdate())