我想知道当天的名字和当月的日期。有人可以帮忙吗?
我想要各自的格式。
Date Day
2018-04-01 Sunday
2018-04-02 Monday
2018-04-03 Tuesday
.
.
.
.
.
.
.
2018-04-30 Monday
答案 0 :(得分:3)
获得所需结果的一种方法是使用递归CTE:
with dates as (
select datefromparts(year(getdate()), month(getdate()), 1) as dte
union all
select dateadd(day, 1, dte)
from dates
where day(dateadd(day, 1, dte)) <> 1
)
select dte, datename(weekday, dte)
from dates;
Here是一个SQL小提琴。
答案 1 :(得分:0)
MJH是对的,如果你想要这样的东西,请使用Calendar表。例如:http://www.sqlservercentral.com/articles/calendar/145206/
然后你的SQL变得像
一样简单SELECT CalendarDate, [DayName]
FROM CalendarTable
WHERE CalendarDate BETWEEN CONVERT(date, DATEADD(MONTH, DATEDIFF(MONTH,0,GETDATE()),0)) AND CONVERT(date, DATEADD(DAY, -1,DATEADD(MONTH, DATEDIFF(MONTH,0,GETDATE()) +1,0)));
或甚至可能:
SELECT CalendarDate, [DayName]
FROM CalendarTable
WHERE CalenderMonth = MONTH(GETDATE())
AND CalendarYear = YEAR(GETDATE());