如何将我的列数与月份数转换为月份名称?
例如:
我有月份列,它有7,7 ,8,9但我希望它显示为7月,7月,8月,9月。
答案 0 :(得分:0)
试试这个...
DECLARE @MonthNumber int
SET @MonthNumber = 1
SELECT DATENAME(MONTH, DATEADD(MONTH, @MonthNumber, '2017/12/31')) AS 'Month'
或者
SELECT DATENAME(MONTH, DATEADD(MONTH, yourColumnHere, '2017/12/31')) AS 'Month'
答案 1 :(得分:0)
如果该列包含月份数的CSV,请尝试此操作(SQL_Server 2016)
DECLARE @t TABLE (
Months_csv NVARCHAR (15)
);
INSERT INTO @t
(
Months_csv
)
VALUES
(
N'7,7,8,9'
);
SELECT
value
,[MonthName]=DATENAME(MONTH, DATEADD(MONTH, CAST(value AS INT), -1))
FROM
@t T
CROSS APPLY
STRING_SPLIT(T.Months_csv, ',');
输出
value MonthName
7 July
7 July
8 August
9 September
如果它不是CSV列表,请尝试此
DECLARE @t TABLE (
Months_ int
);
INSERT INTO @t
(
Months_
)
VALUES
(7),(7),(8),(9);
SELECT
T.Months_
,[MonthName]=DATENAME(MONTH, DATEADD(MONTH, T.Months_, -1))
FROM
@t T
输出
Months_ MonthName
7 July
7 July
8 August
9 September
答案 2 :(得分:0)
使用此Udf
{{ form }}
结果
CREATE FUNCTION [dbo].[udf_GetMonthNAME]
(
@string nvarchar(max)
)
RETURNS @OutTable TABLE
(
MonthNames nvarchar(max)
)
AS
BEGIN
DECLARE @Temp AS TABLE
(
MonthNumber nvarchar(max)
)
INSERT INTO @Temp
SELECT @string
INSERT INTO @OutTable(MonthNames)
SELECT STUFF((SELECT ', '+MonthNumber
FROM
(
SELECT DATENAME(MONTH,DATEADD(MONTH,MonthNumber-5,Getdate())) AS MonthNumber
FROM
(
SELECT CAST(Split.a.value('.','nvarchar(max)') AS INT) AS MonthNumber
FROM
(
SELECT CAST('<S>'+REPLACE(MonthNumber,',','</S><S>')+'</S>' AS XML ) AS MonthNumber
FROM @Temp
)AS A
CROSS APPLY MonthNumber.nodes('S') AS Split(a)
)fn
)fnl FOR XML PATH ('')),1,1,'')
RETURN
END
SELECT * FROM [dbo].[udf_GetMonthNAME] ('7,7,8,9')
GO