x

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

avatar image

sqlLearner 1
972 39 50 57

(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, 2012 at 04:18 PM

avatar image

Kev Riley ♦♦
63.8k 48 61 81

@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.

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

SQL Server Central

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

Topics:

x389
x30

asked: Mar 01, 2012 at 04:10 PM

Seen: 990 times

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

Copyright 2016 Redgate Software. Privacy Policy