zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    渣渣菜鸡的蚂蚁金服面试经历(一)
    20 个案例教你在 Java 8 中如何处理日期和时间?
    Spring Boot 2.0系列文章(七):SpringApplication 深入探索
    分布式锁看这篇就够了
    Spring Boot 2.0系列文章(五):Spring Boot 2.0 项目源码结构预览
    20135337朱荟潼——实验三
    20135337朱荟潼Java实验报告二
    5337朱荟潼Java实验报告一
    Linux内核设计笔记12——内存管理
    Linux内核设计笔记11——定时器
  • 原文地址:https://www.cnblogs.com/ArtlessBruin/p/7125681.html
Copyright © 2011-2022 走看看