sql 根据开始 结束时间 获取年月日季度
CREATE FUNCTION [dbo].[GetDateList]
(
@StartTime DATE,
@EndTime DATE,
@DateType TINYINT
)
RETURNS @DataTab TABLE (
id INT IDENTITY(1,1),
FormatDate NVARCHAR(20),
DateFullInt Int,
DateVal_Y INT,
DateVal_M INT,
DateVal_D INT,
DateVal_Q INT
)
AS
BEGIN
DECLARE @DateVal DATE;
DECLARE @FormatDate NVARCHAR(20);
DECLARE @DateFullInt INT ;
SET @DateVal=@StartTime
WHILE @DateVal <=@EndTime
BEGIN
IF (@DateType=1)
BEGIN
SET @FormatDate=CONVERT(NVARCHAR(10),@DateVal,120)
SET @DateFullInt =CONVERT(INT,REPLACE(@FormatDate,'-',''))
END
IF (@DateType=2)
BEGIN
SET @FormatDate=CONVERT(NVARCHAR(7),@DateVal,120)
SET @DateFullInt =CONVERT(INT,REPLACE(@FormatDate,'-',''))
END
IF (@DateType=3)
BEGIN
SET @FormatDate=CONVERT(NVARCHAR(4),DATEPART(YEAR,@DateVal)) +'-Q'+CONVERT(NVARCHAR(1),DATEPART(QUARTER,@DateVal))
SET @DateFullInt =CONVERT(INT,CONVERT(NVARCHAR(4),DATEPART(YEAR,@DateVal))+'0'+DATEPART(QUARTER,@DateVal))
END
INSERT INTO @DataTab (DateVal_Y,DateVal_M,DateVal_D,DateVal_Q,FormatDate,DateFullInt)
VALUES
(DATEPART(YEAR,@DateVal),
DATEPART(MONTH,@DateVal),
DATEPART(DAY,@DateVal),
DATEPART(QUARTER,@DateVal),
@FormatDate,
@DateFullInt
)
IF (@DateType=1) BEGIN SET @DateVal=DATEADD(DAY,1,@DateVal) END
IF (@DateType=2) BEGIN SET @DateVal=DATEADD(MONTH,1,@DateVal) END
IF (@DateType=3) BEGIN SET @DateVal=DATEADD(QUARTER,1,@DateVal) END
END
RETURN
END
GO
这是一个sql 函数
调用方式
SELECT * FROM GetDateList('2019-01-01','2012-01-10',1)
参数是,(开始时间,结束时间,类型) 类型:1天数,2月份,3季度
下面是查出来的数据
天数:
月份:
季度: