我想知道如何根据当前日期在sql server的列中插入工作日名称。我想插入当天的日子。例如,我想要今天(2014-12-04)的以下专栏,
day_of_week
-----------
Monday
Tuesday
Wednesday
Thursday
在下周二(2014-12-09),我想显示,
day_of_week
-----------
Monday
Tuesday
请告诉我如何在sql server 2012中执行此操作?
任何帮助将不胜感激。
感谢。
答案 0 :(得分:2)
这样的事情应该有效。
select datename(weekday,n)
from (VALUES (0),(1),(2),(3),(4),(5),(6)) wdays(n)
where n < datepart(weekday,'20141209') - 1
如果您没有使用sql 2008及以上,则可以
select datename(weekday,n)
from (select 0
union all
select 1
union all
select 2
union all
select 3
union all
select 4
union all
select 5
union all
select 6
) wdays(n)
where n < datepart(weekday,'20141209') - 1
答案 1 :(得分:1)
也可以使用递归CTE来完成:
;WITH cte AS
(
SELECT DATENAME(weekday,getdate()) AS NameOfDay,
DAY(getdate()) AS NumberOfDay,
getdate() AS curDate
UNION ALL
SELECT DATENAME(weekday,DATEADD(day, -1, curDate)) As NameOfDay,
DAY(DATEADD(day, -1, curDate)) AS NumberOfDay,
DATEADD(day, -1, curDate) AS curDate
FROM cte
WHERE DAY(GETDATE()) - DAY(DATEADD(day, -1, curDate)) >= 0
)
SELECT NameOfDay
FROM cte
ORDER BY NumberOfDay