• sql获取日期区间(年、月、周、日)


    通过存储过程获取当前日期(或指定日期)所在的日期区间,包含年、月、周、日。

    CREATE PROCEDURE [dbo].[GetDataPeriod]
        @defaultDate DATE=NULL,
        @period VARCHAR(1)=NULL,
        @startDate DATE OUTPUT,
        @endData DATE OUTPUT
    AS
    BEGIN
        IF    @defaultDate IS NULL
        BEGIN
            SET @defaultDate=GETDATE();
        END
        IF    @period IS NULL
        BEGIN
            SET @period='M';
        END
        --第一天
        SELECT @startDate=
            CASE @period
            WHEN 'Y' THEN DATEADD(YEAR, DATEDIFF(YEAR,0,@defaultDate), 0)
            WHEN 'M' THEN DATEADD(MONTH, DATEDIFF(MONTH,0,@defaultDate), 0)
            WHEN 'W' THEN DATEADD(WEEK, DATEDIFF(WEEK,0,@defaultDate), 0)
            WHEN 'D' THEN DATEADD(DAY, DATEDIFF(DAY,0,@defaultDate), 0)
            END;
        IF @defaultDate<@startDate
        BEGIN
            SET @defaultDate=DATEADD(DAY,-1,@defaultDate);
            EXEC dbo.GetDataPeriod @defaultDate,@period,@startDate OUTPUT,@endData OUTPUT;
        END
        ELSE
        BEGIN
        --最后一天
        SELECT @endData=
            CASE @period
            WHEN 'Y' THEN DATEADD(DAY,-1,DATEADD(YEAR,1,DATEADD(YEAR, DATEDIFF(YEAR,0,@defaultDate), 0)))
            WHEN 'M' THEN DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(MONTH, DATEDIFF(MONTH,0,@defaultDate), 0)))
            WHEN 'W' THEN DATEADD(DAY,-1,DATEADD(WEEK,1,DATEADD(WEEK, DATEDIFF(WEEK,0,@defaultDate), 0)))
            WHEN 'D' THEN DATEADD(DAY, DATEDIFF(DAY,0,@defaultDate), 0)
            END;
        END
    END
    

    使用实例

    DECLARE @startDate DATE,
        @endData DATE;
    EXEC dbo.GetDataPeriod @defaultDate = '2017-06-20',
        @period = 'Y',
        @startDate = @startDate OUTPUT,
        @endData = @endData OUTPUT
    SELECT @startDate,@endData;--// 2017-01-01 2017-12-31
     
    EXEC dbo.GetDataPeriod @defaultDate = '2017-06-20',
        @period = 'M',
        @startDate = @startDate OUTPUT,
        @endData = @endData OUTPUT
    SELECT @startDate,@endData;--// 2017-06-01 2017-06-30
     
    EXEC dbo.GetDataPeriod @defaultDate = '2017-06-20',
        @period = 'W',
        @startDate = @startDate OUTPUT,
        @endData = @endData OUTPUT
    SELECT @startDate,@endData;--// 2017-06-19 2017-06-25
     
    EXEC dbo.GetDataPeriod @defaultDate = '2017-06-20',
        @period = 'D',
        @startDate = @startDate OUTPUT,
        @endData = @endData OUTPUT
    SELECT @startDate,@endData;--// 2017-06-20 2017-06-20
    
  • 相关阅读:
    CRISPR Screening的应用
    Trios | 家系研究
    高通量测序数据的存储、分析和管理
    glusterfs部署及卷类型使用【转】
    perf的使用方法(CPU占用高分析)【转】
    MGR的gtid_executed不连续的问题分析【转】
    Ceph存储使用【转】
    Pycharm2018激活(含软件下载)【转】
    Jupyter notebook添加kernel【转】
    Kubernetes零宕机滚动更新【转】
  • 原文地址:https://www.cnblogs.com/ArtlessBruin/p/7125681.html
Copyright © 2020-2023  润新知