存储过程以填充日历

时间:2011-05-09 09:44:41

标签: sql sql-server

我想在一个SQL Server中填写表“日历”,点击vb.net表单中的按钮,我必须填写下一列:date,week_weekend(这个日期是一周还是周末),当天的名称(星期一,星期二,......),period_name(季节,假日),code_schoolholiday(y或N),code_holiday(圣诞节,新年等)。

1 个答案:

答案 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

您需要缩小对其余数据的要求:

  1. 定义季节的名称和标准,以确定每一天的季节 - 我相信您可以在这里再次轻松使用DATEPART功能。
  2. 学校假期发生在每个国家的不同日子,甚至是大国的每个地区。缩小范围。此外,在某些国家(如波兰),在某些年份,在周末和银行假日之间增加了额外的免费日,以延长假期,作为交换,孩子们会在一周后的星期六上学。
  3. 定义您理解的假期 - 免费日?特殊宗教仪式/活动发生的日子?如果是这样那么宗教,国家,宗教的味道呢?我相信DATEPART功能将再次成为你的好朋友。
  4. 确定新年前夕:

    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)
    
相关问题