Question

SELECT LEFT(201404, 4) + 2 

Is only giving me 2016, I want the result to be an int as: 201604

how can I do that?

Était-ce utile?

La solution

DECLARE @String VARCHAR(6) = '201404';
SELECT CAST((CAST(LEFT(@String, 4) AS INT) + 2) AS VARCHAR(4))  + RIGHT(@String, 2) 

Autres conseils

it is not as hard as you think

SELECT 201404 + 2*100

You really need to be aware of the dataypes involved. Are you are performing this operation on a VARCHAR or INT field in a table?

A reliable way to do this (i.e. it crosses year boundaries and will give you a result of 201412 + 2 = 201502, not 201414) is to convert to date, use dateadd to add months, and convert back.

This example assumes it is stored as VARCHAR

First add 01 to the end do give it a dummy day and make it look like a full date:

SELECT YourField+'01'

Now convert this to a date using code 112 (format yyyymmdd)

SELECT CONVERT(
    DATE,
    YourField+'01',
    112
    )

Now add two months to this:

SELECT 
    DATEADD(mm,2,
      CONVERT(
        DATE,
        YourField+'01',
        112
      )
    )

Now convert back to varchar, trimming it down to 6 characters (trimming the trailing 01:

SELECT 
    CONVERT(VARCHAR(6),
      DATEADD(mm,2,
        CONVERT(
          DATE,
          YourField+'01',
          112
        )
      ),
    112)

You should almost certain use a datetime field, or if using newer version of sql a date field.

Then use the dateadd() e.g.

select dateadd(year, '2014-04-01', 2)

You can then use convert() to convert the final result to a number of different string formats if desired. Or you can use datepart() to extract year, month, etc.

I am assuming your example is a little messed up since 201404 is not really a valid date format. My example is based on assuming you mean the first of the month

Try this

select convert(varchar(6),dateadd(year,2,cast(cast(201404 as varchar)+'01' as date)),112)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top