Link to home
Start Free TrialLog in
Avatar of twfw123
twfw123

asked on

SL Server 2008 yyyymm +1

Hi - I have a question that I would like assistance with - Im sure this will be a quick one but i keep missing at the moment...
What is the best way to add a month to a YYYYMM dataset in a sql server table.
for example I have a set of dates
201501
201502
that I would like to change to the following
201501  to 201502
201502  to 201503
what would be the best method to achieve this ?
Avatar of Lee
Lee
Flag of United Kingdom of Great Britain and Northern Ireland image

select convert(nvarchar(6), DATEADD(mm , 1 , cast(myDateField + '01')), 112)

Open in new window

The best way: Not violating 1 NF.
Oops, syntax error:

select convert(nvarchar(6), DATEADD(mm , 1 , cast(myDateField + '01' as datetime)), 112)

Open in new window

What data type has your "date" column?
I would have assumed that if the format is YYYYMM then it is likely to be a nvarchar() field. It could be an integer I suppose, but my conversion leaves it as a nvarchar(6) field.
Avatar of twfw123
twfw123

ASKER

the field is INT
Then you could alter my statement this way:

select cast(convert(nvarchar(6), DATEADD(mm , 1 , cast(myDateField + '01' as datetime)), 112) as integer)

Open in new window

With my way, you are making SQL determine the correct date by treating it as a date, and then converting back to a 6 char string in the form, YYYYMM, and finally to an integer which will give you what you need.
@Lee: You need to convert the INT explicitly to VARCHAR before adding '01'. Otherwise type precedence will come into play.
That's true.

select cast(convert(nvarchar(6), DATEADD(mm , 1 , cast(cast(myDateField as integer) + '01' as datetime)), 112) as integer)

Open in new window


You may need to cater for blank fields in a where clause.
first explicitly convert the int value to varchar so you can add the string '01'
       convert(varchar(6),@val) + '01'
convert that  (YYYYMMDD string) to date
add 1 month to that date
then convert to 'YYYYMM' string (6 chars)
convert that string to int

then: take a breath, repeat

declare @val int = 201512

set @val = convert(int,convert(varchar(6),dateadd(month,1,convert(date,convert(varchar(6),@val) + '01')),112))

-- result = 201601

Open in new window


tedious in the extreme
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
sanity prevails. use Scott's
Avatar of twfw123

ASKER

thanks for the assistance, Paul yes Scott offers a very nice method...