DateAdd problem

I am trying to subtract 1 month from the current YearMOnth...It's datatype is a varchar(6)

Current    HowIwant
201001     200912

I am using this but not getting the correct result

SELECT yearmonth, dateadd(M, datediff(month, 0, yearmonth) - 1, 0)
from tableA
more ▼

asked Mar 01, 2012 at 04:10 PM in Default

sqlLearner 1 gravatar image

sqlLearner 1
802 36 42 47

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

You can't use datetime functions on varchar like that - it has no idea that the string is supposed to represent 'yyyymm'

try this

    dateadd(M, datediff(month, 0, convert(date, yearmonth +'01', 112)) - 1, 0)
This converts your string +'01', which is the style 112, to a date, and then does the dateadd manipulation.
more ▼

answered Mar 01, 2012 at 04:18 PM

Kev Riley gravatar image

Kev Riley ♦♦
53.9k 47 49 76

@kev Riley That works but produces the answer in the format 2009-11-01 00:00:00.000
Mar 01, 2012 at 04:33 PM sqlLearner 1
sorry missed off the final convert.....edited!
Mar 01, 2012 at 04:45 PM Kev Riley ♦♦
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.



asked: Mar 01, 2012 at 04:10 PM

Seen: 867 times

Last Updated: Mar 01, 2012 at 04:47 PM