if exists(Select 1 fromsysobjectswhereType='TF' andName='atpublic_tf_getsummarydate') Drop functionatpublic_tf_getsummarydateGoCreate functionAtpublic_tf_getsummarydate (@calltype varchar(1)="',--0: Year 1: Month 1: Day @startdateDATE,--Start Date @enddateDATE--End Date) /** * author:create date:2018-01-18 Description: Loop return Date Example: * **/RETURNS @retDateValue TABLE(DateValuevarchar( +)) as begin if @calltype='0' begin Insert into @retDateValue(datevalue)Select substring(Convert(varchar( +),DATEADD( Year, Number,@startdate), +),1,4) asYearvalue fromMaster.. Spt_valuesWHERETYPE= 'P' and DATEADD( Year, Number,@startdate)<= @enddate End Else if @calltype='1' begin Insert into @retDateValue(datevalue)Select substring(Convert(varchar( +),DATEADD(MONTH, Number,@startdate), +),1,7) asYearvalue fromMaster.. Spt_valuesWHERETYPE= 'P' and DATEADD(MONTH, Number,@startdate)< @enddate End Else if @calltype='2' begin Insert into @retDateValue(datevalue)Select Convert(varchar( +),DATEADD( Day, Number,@startdate), +)+'00:00:00' asYearvalue fromMaster.. Spt_valuesWHERETYPE= 'P' and DATEADD( Day, Number,@startdate)< @enddate End returnEnd Go
Invocation Example:
Declare @beginDate varchar( +)="',@endDate varchar( +)="',@datebefore datetimeSelect @beginDate='2017-01-01',@endDate='2017-05-31'Select @datebefore=CONVERT(datetime,@beginDate)SelectDateValue fromAtpublic_tf_getsummarydate ('0',@beginDate,@endDate)SelectDateValue fromAtpublic_tf_getsummarydate ('1',@beginDate,DateAdd( Year,1,@datebefore))SelectDateValue fromAtpublic_tf_getsummarydate ('1',@beginDate,DateAdd(MONTH,1,@datebefore))SelectDateValue fromAtpublic_tf_getsummarydate ('2',@beginDate,DateAdd(MONTH,1,@datebefore))
SQL Server gets the consecutive year, month, day