Home SQL Setting Variable for Current Year Month by Combining two VarChar fields using case statement
Reply: 0

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

user786
1#
user786 Published in June 19, 2018, 4:14 pm

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;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.414875 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO