Wednesday, March 21, 2012

parse data and then compare

I am using MSSQL v8 (if that matters)

The data looks like the following
--------
| PBP 20070420 2:26pm |
--------

Now the data in this field is not uniform it can be blank, a sentence or have a different pre fix, instead of PBP, but the date will be YYYYMMDD when it is supplied.

I need to find all the dates that are within the last 10 months. How do I perform this task?yes, it matters -- moving thread to SQL Server forum

will the date always always follow the first space?|||you're going to have to supply more than 1 sample row|||Sorry about the inactivity, i have been busy with reviews.

The date will always be after the first spaces if the date is supplied.

Now I did not write the database or the program, just generating reports from it, so i am not responsible for the disorganization. The filed was originally a list of cities, so there are still some city names in this field, along with blank data, and the data we need.

The data we need is formated as [<username> <YYYYMMDD> <time>]
here are some examples

--------
| MCG 20050624 1:28pm |
--------
| PBP 2005072711:38am |
--------
| |
--------
| Atlanta |
--------
| JM 20050721 4:48pm |
--------

This shows the 3 types of data that i encounter in this table.|||The date will always be after the first spaces if the date is supplied.Your sample data suggest more than one space. Is the <username> a fixed length then use substring to get the date part else
use patindex to find the starting position of the date.
select c1=
'MCG 20050624 1:28pm' into #t1 union all select
'PBP 20050727 11:38am' union all select
'' union all select
'Atlanta' union all select
'JM 20050721 4:48pm' union all select
'PBP 20070420 2:26pm'

select c1 from #t1
where patindex('% [12][0-9][0-9][0-9][01][0-9][0-3][0-9]%',c1)>0
and dateadd(mm,-10,getdate())<(substring(c1,patindex('% [12][0-9][0-9][0-9][01][0-9][0-3][0-9]%',c1)+1,26))

drop table #t1

No comments:

Post a Comment