x
login about faq Site discussion (meta-askssc)

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 '12 at 04:10 PM in Default

sqlLearner 1 gravatar image

sqlLearner 1
542 13 28 33

(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

SELECT 
 left(
  convert(varchar, 
    dateadd(M, datediff(month, 0, convert(date, yearmonth +'01', 112)) - 1, 0)
    ,112)
 ,6)

This converts your string +'01', which is the style 112, to a date, and then does the dateadd manipulation.

more ▼

answered Mar 01 '12 at 04:18 PM

Kev Riley gravatar image

Kev Riley ♦♦
46k 38 43 69

@kev Riley That works but produces the answer in the format 2009-11-01 00:00:00.000

Mar 01 '12 at 04:33 PM sqlLearner 1

sorry missed off the final convert.....edited!

Mar 01 '12 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.

Follow this question

By Email:

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

By RSS:

Answers

Answers and Comments



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x224
x40

asked: Mar 01 '12 at 04:10 PM

Seen: 417 times

Last Updated: Mar 01 '12 at 04:47 PM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.