我试图遍历Common Table Expressions,并决定编写一个返回月份名称的cte。
with cte_month(n, monthname)
as
(
select 0, datename(m,0)
union all
select n+1,datename(m,n+1)
from cte_month
where n < 11
)
select monthname from cte_month;
对应的工作日cte工作正常,
WITH cte_numbers(n, weekday)
AS (
SELECT
0,
DATENAME(DW, 0)
UNION ALL
SELECT
n + 1,
DATENAME(DW, n + 1)
FROM
cte_numbers
WHERE n < 6
)
SELECT
weekday
FROM
cte_numbers;
但是这个月的日期怎么了?
DATENAME
的第二个参数是一个日期,不是int型,所以使用int值创建一个日期…
with cte_month(n, monthname)
as
(
select 1, datename(m,0)
union all
select n+1,datename(m,DATEFROMPARTS(2021,n+1,1))
from cte_month
where n < 12
)
select * from cte_month;
使用datename(m,0)
可以在初始select
中工作,因为它相当于datename(m,cast(0 as datetime))
,将返回"January"因为SQL Server的基本日期时间是1900-01-01(即一月的日期时间)。