Question

I have a database where, for some reason, the dates are put in like 1yymmdd. I have been asked to create a field in a query that adds 30 days to this date. I have transformed the date into a readable format by the following:

SUBSTRING(Datefield, 4, 2) + '/' + SUBSTRING(Datefield, 6, 2) 
    + '/' + SUBSTRING(Datefield, 2, 2) AS LookLikeDate

I placed this in a view, and attempted to then:

DATEADD(dd,30, CONVERT(datetime, v.[LookLikeDate], 103)

I keep getting an error that says

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

I then attempted to define in my View statement so that this field would be datetime from the start:

CONVERT(datetime, SUBSTRING(Datefield, 4, 2) + '/' 
    + SUBSTRING(Datefield, 6, 2) + '/' 
    + SUBSTRING(Datefield, 2, 2), 103) AS LookLikeDate

When I got an error in that definition, to where I couldn't use the view at all, I changed the datetime to Char(8), which gave me the same varchar error I got previously.

Am I going about this wrong, and is there a way to add these days to this rediculous date format?

Était-ce utile?

La solution

Just to add 30 days you can do

SELECT DATEADD(dd, 30, RIGHT(datefield, 6)) NewDate
  FROM table1

To add 30 days and convert back to that format use

SELECT '1'+ CONVERT(VARCHAR(6), DATEADD(dd, 30, RIGHT(datefield, 6)), 12) NewDate
  FROM table1

If you were to have following sample data

| DATEFIELD |
|-----------|
|   1130801 |
|   1130812 |
|   1120827 |

Then the output of two above mentioned queries would be

|                          NEWDATE |
|----------------------------------|
|    August, 31 2013 00:00:00+0000 |
| September, 11 2013 00:00:00+0000 |
| September, 26 2012 00:00:00+0000 |

and

| NEWDATE |
|---------|
| 1130831 |
| 1130911 |
| 1120926 |

respectively.

Here is SQLFiddle demo

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top