根據年,自動生成日期

2021-09-08 15:24:31 字數 2914 閱讀 3811

引數為 @year,表示年份,然後自動返回當年所有的日期,格式為:

date         week                             note

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

20080101 星期二                            null

20080102 星期三                            null

20080103 星期四                            null

.... ...

20081228 星期日                            null

20081229 星期一                            null

20081230 星期二                            null

20081231 星期三                            null

usetest

goif

object_id('

usp_calendar') 

isnot

null

drop

proc

usp_calendar

gocreate

proc

usp_calendar

(@year

int)

asdeclare

@startdate

datetime

,@enddate

datetime

ifisdate

(rtrim

(@year)+

'0101')

=0return

select

@startdate

=rtrim

(@year)+

'0101',

@enddate

=rtrim

(@year)+

'1231';

with

t0 as

(selectid=

1union

allselectid=

1),t1 as

(select

a.id 

from

t0 a,t0 b),

t2 as

(select

a.id 

from

t1 a,t1 b),

t3 as

(select

a.id 

from

t2 a,t2 b),

t4 as

(selectid=

row_number() 

over

(order

bya.id) 

from

t3 a,t1 b)

select

date

=convert

(char(8

),@startdate+id

-1,112

),week

=datename

(dw,

@startdate+id

-1),note

=null

from

t4where

id<=

datediff

(day

,@startdate

,@enddate)+

1goexec

usp_calendar 

2008go

另,考慮只是查詢一年,使用遞迴的cte:

usetest

goif

object_id('

usp_calendar') 

isnot

null

drop

proc

usp_calendar

gocreate

proc

usp_calendar

(@year

int)

asdeclare

@startdate

datetime

,@enddate

datetime

ifisdate

(rtrim

(@year)+

'0101')

=0return

select

@startdate

=rtrim

(@year)+

'0101',

@enddate

=rtrim

(@year)+

'1231';

with

t as

(    

selectid=

convert

(int,0

),date

=@startdate

,week

=convert

(nvarchar(20

),@startdate

)union

allselectid=

convert

(int

,id+

1),date

=date+1

,week

=convert

(nvarchar(20

),date+1

)from

t where

date

<

@enddate

)select

date,week,note

=null

from

t option

(maxrecursion 0)

goexec

usp_calendar 

2008go

MSSQL Server自動生成日期加數字的序列號

需求 需要生成下面的序列號,前半部分是yyyymmdd格式的年月日時間數字,後半部分則是每天都從1順序增長的數字,位數要固定,中間不足的補0。在sql server 2000資料庫中測試後通過如下 功能實現如下 use master goif exists select from dbo.sysda...

MSSQL生成日期列表

title generating test data author wufeng4552 date 2009 09 28 08 52 38 if exists select from dbo.sysobjects where id object id n dbo f getdate and xtyp...

linux crontab e生成日期格式

近期公司資料庫伺服器要上雙活專案,實施顧問要收集伺服器 磁碟效能資料 io及vm的一些相關資訊,並已日期時間格式生成檔案 用crontab e增加以下內容,它的作用是每隔1個小時啟動一次iostat和vmstat,iostat的間隔為10秒,共360次,即為1個小時。以下是顧問給的指令碼,直接在終端...