我想在一个SQL Server中填写表“日历”,点击vb.net表单中的按钮,我必须填写下一列:date,week_weekend(这个日期是一周还是周末),当天的名称(星期一,星期二,......),period_name(季节,假日),code_schoolholiday(y或N),code_holiday(圣诞节,新年等)。
答案 0 :(得分:1)
要查找星期几,请使用select DATEPART(weekday, _date_goes_here_)
,这会为您提供代表当天的数字。您可以使用以下代码获取今天的日期名称:
-- EDIT as Martin rightly pointed out, you need to take
-- @@datefirst into account here's a version of code which will
-- return the right dayname regardless of this variable's value
select case DATEPART(weekday, getdate() + @@datefirst)
when 1 then 'Sunday'
when 2 then 'Monday'
when 3 then 'Tuesday'
when 4 then 'Wednesday'
when 5 then 'Thursday'
when 6 then 'Friday'
when 7 then 'Saturday'
end
您还可以轻松了解当天是否是周末:
select case DATEPART(weekday, getdate())
when 1 then 'weekend'
when 7 then 'weekend'
else 'weekday'
end
有关DATEPART
函数at MSDN
现在要插入包含大量日期和计算数据的大量行,您需要以下代码的变体(今天和99天之后选择,当然您需要用INSERT
语句包装它):
select v1.x * 10 + v2.x as dayoffset
, cast((GETDATE() + v1.x * 10 + v2.x) as DATE) as calendardate
, case DATEPART(weekday, cast((GETDATE() + v1.x * 10 + v2.x) as DATE))
when 1 then 'Sunday'
when 2 then 'Monday'
when 3 then 'Tuesday'
when 4 then 'Wednesday'
when 5 then 'Thursday'
when 6 then 'Friday'
when 7 then 'Saturday'
end as dayname
from (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (0)) v1(x)
cross join (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (0)) v2(x)
order by v1.x * 10 + v2.x
您需要缩小对其余数据的要求:
DATEPART
功能将再次成为你的好朋友。确定新年前夕:
select d, case
when DATEPART(month, d) = 12 and DATEPART(DAY, d) = 31 then 'New years eve'
else 'other day'
end
from (
select CAST('2010-12-31' as datetime)
union
select GETDATE()
) t(d)