SQL Setting Variable for Current Year Month by Combining two VarChar fields using case statement

ぃ、小莉子 提交于 2020-04-18 05:18:00

问题


I am trying to declare a variable for the current year and month based on a field called YEARMO.

It's a 6 character varchar field with the first 4 characters representing the year and the next 2 characters representing the month (ex. February 2018 as 201802).

I need the month variable to have a 0 in front of it if is a month that only has one digit (any month before October). Current code returns '20182' and would like it to return '201802'.

declare @current_month varchar(6)

set @current_month = CAST( year(getdate()) as varchar(4)) 
+ case when  len(CAST( month(getdate()) as varchar(2))) < 1 then '0' + 
CAST( month(getdate()) as varchar(2)) 
else CAST( month(getdate()) as varchar(2))
end

select @current_month;

回答1:


Your code is over complicated. Use right instead:

declare @current_month char(6)
set @current_month = CAST( year(getdate()) as varchar(4)) + right('00' + cast(month(getdate()) as varchar(2)), 2)
select @current_month;

Result:

201802

If you really want to use case instead, you should change the 1 to 2:

set @current_month = CAST( year(getdate()) as varchar(4)) + 
                     case when len(CAST(month(getdate()) as varchar(2))) < 2 then 
                     '0' + CAST( month(getdate()) as varchar(2)) else 
                     CAST( month(getdate()) as varchar(2)) end



回答2:


You can use Convert function if you are looking for current month

select convert(char(6), getdate(), 112)



回答3:


declare @current_month varchar(6)

set @current_month = CAST(year(getdate())*100 + month(getdate()) as varchar(6))



来源:https://stackoverflow.com/questions/48770533/sql-setting-variable-for-current-year-month-by-combining-two-varchar-fields-usin

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