Click here to Skip to main content
16,016,712 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
Hi there.

I am trying to add strings which are integers. I have 201404 as input and I need it to be converted to 201503 so the only way to do this is to increase the year (2014) by 1 and decrease the month 02 by 1. 
I have tried the below but the leading zero in the month does not seem to preserve


C#
declare
     @YearMonth int =201404,
     @left int = 0,
     @right int= 0

 SET @YearMonth= CAST(@YearMonth AS VARCHAR(6))
  set @left = cast(left(@YearMonth,4) +1   as varchar(max))
  set @right = right(@YearMonth,2) - 1
  set @right = cast(@right as varchar(2))

 SET @right = RIGHT(('0' + Cast(@right as varchar(2))),2)

 print @left

 print RIGHT( '0' + LTRIM( RTRIM( @right ) ), 6 )
Posted
Updated 20-Nov-15 2:25am
v2

Why do you convert to string at all ?
SQL
declare
    @YearMonth int =201404,
set @YearMonth= @YearMonth + 99
print @YearMonth
 
Share this answer
 
v2
I believe the problem is because you are treating integers like strings.
03 is not a valid integer so it gets converted to 3.
The rest of the convertions from int to varchar and back is the server helping you out a lot.

However, with what you have you can get to the final value you are looking for.

This should work...
SQL
print cast(@left as varchar(4)) + replicate('0', 2-len(@right)) + cast(@right as varchar(2))
 
Share this answer
 
Change your DB.
Don't store dates (even partial dates) as strings: always store them as DATE or DATETIME - that way, you can be sure they are all valid dates, and use the built in functions such as DATEPART and DATEADD. In you case, just set the day part to the first of teh month, and the time to midnight.

Storing any numeric data as strings always gives a lot more problems than it solves in the long run.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900