如何将SQL Server中'yyyymm'格式字符转换为Mon-yyyy日期格式?
解决方案
要将格式为YYYYMM的字符型YearMonth转换为Mon-YYYY格式,你可以通过先转换为日期类型,再格式化输出的方式实现,以下是两种适配不同SQL Server版本的方案:
方案1:使用FORMAT函数(SQL Server 2012及以上版本)
FORMAT函数可直接将日期格式化为指定字符串样式,修改代码如下:
declare @CoverageYear Char(4); -- Month being inserted declare @CoverageMonth Char(2); -- Year being inserted set @CoverageYear = Year(getdate()); -- Run for the current coverage year set @CoverageMonth = case when Month(getdate()) <= 9 then '0' + cast(Month(getdate()) as char(1)) -- Run for the current coverage month else cast(Month(getdate()) as char(2)) end; -- 转换为Mon-YYYY格式 select FORMAT(CAST(@CoverageYear + @CoverageMonth + '01' AS DATE), 'MMM-yyyy', 'en-US') AS FormattedYearMonth
- 先拼接
YYYYMM为YYYYMMDD(补01作为当月第一天),转换为DATE类型 - 用
FORMAT函数指定'MMM-yyyy'样式,'en-US'确保月份是英文缩写
方案2:使用DATENAME拼接(兼容所有SQL Server版本)
如果你的SQL Server版本低于2012,可通过截取月份名称缩写实现:
declare @CoverageYear Char(4); -- Month being inserted declare @CoverageMonth Char(2); -- Year being inserted set @CoverageYear = Year(getdate()); -- Run for the current coverage year set @CoverageMonth = case when Month(getdate()) <= 9 then '0' + cast(Month(getdate()) as char(1)) -- Run for the current coverage month else cast(Month(getdate()) as char(2)) end; -- 转换为Mon-YYYY格式 select LEFT(DATENAME(MONTH, CAST(@CoverageYear + @CoverageMonth + '01' AS DATE)), 3) + '-' + @CoverageYear AS FormattedYearMonth
- 同样先转换为日期类型,用
DATENAME(MONTH, ...)获取月份全称(如January) - 用
LEFT截取前3个字母得到缩写,再拼接年份
若处理表中的YearMonth列(而非变量),只需把变量替换为列名即可,例如:
SELECT LEFT(DATENAME(MONTH, CAST(YearMonth + '01' AS DATE)), 3) + '-' + LEFT(YearMonth, 4) AS FormattedYearMonth FROM YourTableName
内容的提问来源于stack exchange,提问作者GulfFoxtrot28
相关产品推荐
相关产品推荐

