MSSQL 根據年月生成日曆函式

2021-06-03 20:14:13 字數 2572 閱讀 6439

go

create function fn_calendar(@year int, @month int)

returns nvarchar(max)

asbegin

declare @result nvarchar(max), @enter nvarchar(8)

select @enter = char(13)+char(10), @result = ' sun mon tue wed thu fri sat' + @enter --表頭

declare @start datetime, @end datetime

select @start = rtrim(@year)+'-'+rtrim(@month)+'-1', @end = dateadd(mm, 1, @start)

set @result = @result+replicate(' ', (datepart(dw, @start)+@@datefirst+6)%7) --第一行前面的空格

while datediff(d, @start, @end)>0

begin

if (datepart(dw, @start)+@@datefirst)%7 = 1

select @result = @result+@enter --是否換行

select @result = @result+right(' '+rtrim(day(@start)), 4), @start = dateadd(d, 1, @start)

endreturn @result

endgo

--測試示例

set datefirst 3

print dbo.fn_calendar(2007, 12)

select dbo.fn_calendar(2007, 12)

set datefirst 7

--執行結果

/*sun mon tue wed thu fri sat

12 3 4 5 6 7 8

9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

*/go

create function f_calendar(@year int,@month int)

returns @t table(日varchar(4),一varchar(4),二varchar(4),三varchar(4),四varchar(4),五varchar(4),六varchar(4))

asbegin

declare @a table(id int identity(0,1),date datetime)

insert into @a(date)

select top 31 rtrim(@year)+'-'+rtrim(@month)+'-1' from sysobjects

update @a set date=dateadd(dd,id,date)

insert into @t

select

max(case datepart(dw,date) when 7 then rtrim(day(date)) else '' end),

max(case datepart(dw,date) when 1 then rtrim(day(date)) else '' end),

max(case datepart(dw,date) when 2 then rtrim(day(date)) else '' end),

max(case datepart(dw,date) when 3 then rtrim(day(date)) else '' end),

max(case datepart(dw,date) when 4 then rtrim(day(date)) else '' end),

max(case datepart(dw,date) when 5 then rtrim(day(date)) else '' end),

max(case datepart(dw,date) when 6 then rtrim(day(date)) else '' end)

from

@awhere

month(date)=@month

group by

(case datepart(dw,date) when 7 then datepart(week,date)+1 else datepart(week,date) end)

return

endgo

--測試示例

set datefirst 1

select * from dbo.f_calendar(2007,12)

--執行結果

/*日 一 二 三 四 五 六

---- ---- ---- ---- ---- ---- ----

12 3 4 5 6 7 8

9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

*/

根據年月生成日曆函式

go 建立函式 第一版 dobear 0922 create function fn calendar year int month int returns nvarchar max as begin declare result nvarchar max enter nvarchar 8 sele...

mysql生成日曆指令碼(年 年月 格式)

create table num i int 建立乙個表用來儲存0 9的數字 insert into num i values 0 1 2 3 4 5 6 7 8 9 生成0 9的數字,方便以後計算時間 create table if not exists day date date 生成乙個儲存日...

js生成日曆

演算法 1.根據指定年份和月份,計算該月第一天的起始位置和最後一天的結束位置 2.第乙個單元格到起始位置,填充上個月日期或空白 3.起始位置和結束位置填充該月日期 4.結束位置之後填充下個月日期或空白 效果圖 日曆初始化,預設當前月份日曆 function initcalendar calendar...