1

I have got a table that contains deferent type of date formats:

########
DateTime
########
10/05/2015
11/05/2015
1/5/2015
01/5/2014

Now my question is that How can I select all the rows based on this pattern \d{2}/\d{2}/\d{4} the format the result with this pattern \d{4}/\d{2}/\{2}? The first one is dd/mm/yyyy and I would like the result be yyyy/mm/dd

student
  • 55
  • 6

2 Answers2

1

Test Data

DECLARE @TABLE TABLE (Dates VARCHAR(20))
INSERT INTO @TABLE VALUES 
('10/05/2015'),
('11/05/2015'),
('1/5/2015'),
('01/5/2014')

Query

The following query will convert all the values to proper sql server date data type.

SELECT CONVERT(DATE,
       RIGHT('0000' + PARSENAME(REPLACE(Dates , '/','.'),1),4)
     + RIGHT('00'   + PARSENAME(REPLACE(Dates , '/','.'),2),2)
     + RIGHT('00'   + PARSENAME(REPLACE(Dates , '/','.'),3),2)
      )
FROM @TABLE

Result

2015-05-10
2015-05-11
2015-05-01
2014-05-01

Once you have got the values in well-formatted sql server date type, you can extend the query to get the required output yyyy/mm/dd by doing the following:

SELECT  CONVERT(VARCHAR(10), 
      CONVERT(DATE,
       RIGHT('0000' + PARSENAME(REPLACE(Dates , '/','.'),1),4)
     + RIGHT('00'   + PARSENAME(REPLACE(Dates , '/','.'),2),2)
     + RIGHT('00'   + PARSENAME(REPLACE(Dates , '/','.'),3),2)
      ), 111)
FROM @TABLE

Result

2015/05/10
2015/05/11
2015/05/01
2014/05/01
M.Ali
  • 67,945
  • 13
  • 101
  • 127
0

In your case I you don't need to use regular expressions. A simple LIKE should suffice.

... WHERE DateTime LIKE "__/__/____" ...

Hazzit
  • 6,782
  • 1
  • 27
  • 46