SQL Adding integer strings with zero values

若如初见. 提交于 2019-12-11 18:05:55

问题


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:

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)

回答1:


Dealing with integer YYYYMM format can be difficult when adding and subtracting months. One method is to convert to a number of months, and then convert back to the format. So, this converts the value to a number of months

select (@YearMonth / 100) * 12 + (@YearMonth % 100)

Then we can add a number, such as 11 and convert back to the integer format:

select (( (@YearMonth / 100) * 12 + (@YearMonth % 100) + 11) / 12) * 100 +
        ( (@YearMonth / 100) * 12 + (@YearMonth % 100) + 11) % 12)
       ) as yyyymm

Another method that might be simpler is to use date arithmetic:

select dateadd(11, month, cast(@YearMonth as varchar(255)) + '01')

This returns a date. You can convert it back to the number as:

select (year(dateadd(11, month, cast(@YearMonth as varchar(255)) + '01')) * 100 +
        month(dateadd(11, month, cast(@YearMonth as varchar(255)) + '01'))
       ) as yyyymm



回答2:


Use REPLICATE

replicate('0', 2 - len(@right)) + @right




回答3:


Just ran this:

DECLARE @YearMonth INT = 201404;

SELECT CONVERT(VARCHAR(6), DATEPART(YEAR, T.Data) + 1) + RIGHT(100 + DATEPART(MONTH, T.Data) -1, 2)
FROM (VALUES (CONVERT(VARCHAR(8), @YearMonth) + '01')) AS T(Data);

Result:

201503

It's going to pick month number and add 100 to it and then pick 2 right chars from it, so for instance you got 4, it becomes 104 and then RIGHT function picks last 2 characters, which are 04.

Checked with other params, seems fine:

DECLARE @YearMonth INT = 201411;

SELECT CONVERT(VARCHAR(6), DATEPART(YEAR, T.Data) + 1) + RIGHT(100 + DATEPART(MONTH, T.Data) -1, 2)
FROM (VALUES (CONVERT(VARCHAR(8), @YearMonth) + '01')) AS T(Data);

Result:

201510



回答4:


I would convert implicitly to date, add 11 months and then format back as a string. The integer conversion would be implicit as well.

select format(dateadd(month, 11, str(@YearMonth) + '01'), 'yyyyMM')


来源:https://stackoverflow.com/questions/33826296/sql-adding-integer-strings-with-zero-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!