我有一个要求,我需要从给定日期动态返回月份。
例如,如果输入为libRNPurchases.a
,则输出应为
2018-05-20
答案 0 :(得分:2)
就我个人而言,我将使用统计表而不是rCTE。考虑到您只需要0-11,就可以轻松地“硬编码”值:
DECLARE @Date date = '20180520';
SELECT DATENAME(MONTH,DATEADD(MONTH, V.M, @Date))
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11)) V(M)
ORDER BY V.M;
答案 1 :(得分:0)
您可以尝试使用cte递归。
开始日期是今天,结束日期是明年。
cte recursive
条件是每增加一个月进行一次比较。
查询1 :
;WITH CTE(startDt,endDt) AS (
SELECT CAST('2018-05-20' AS DATE) startDt, DATEADD (year,1,'2018-05-20') endDt
UNION ALL
SELECT DATEADD(month,1,startDt) ,endDt
FROM CTE
WHERE DATEADD(month,1,startDt) < endDt
)
SELECT datename(month, startDt)
FROM CTE
Results :
| |
|-----------|
| May |
| June |
| July |
| August |
| September |
| October |
| November |
| December |
| January |
| February |
| March |
| April |
答案 2 :(得分:0)
满足您的要求吗?
-- TEST DATA
declare @my_date as date = '2018-05-20';
-- SOLUTION
with cte as (
select DATENAME(month,@my_date) name, CAST(1 as int) lvl
union all
select DATENAME(month,dateadd(month,cte.lvl,@my_date)),cte.lvl + 1 from cte where cte.lvl <12
)
select name as [Month Name] from cte;
答案 3 :(得分:0)
您可以尝试以下方式
strdup
答案 4 :(得分:0)
您也可以这样做
DECLARE @Date date = '20180520';
SELECT DATENAME(MONTH,DATEADD(MONTH, V.[Numbers], @Date)) AS Months
FROM (
SELECT TOP (11 - 0+1) ROW_NUMBER() OVER (ORDER BY S.[object_id])+(0 - 1) [Numbers]
FROM sys.all_objects S WITH (NOLOCK)
) V