• 【SQL】How to get First and Last day of a Year – TSQL


    SELECT      DATEADD(YEAR, DATEDIFF(YEAR, 0,
                DATEADD(YEAR, -1, GETDATE())), 0),
                'First Day of Previous Year'
    UNION ALL
    SELECT      DATEADD(MILLISECOND, -3, DATEADD(YEAR,
                DATEDIFF(YEAR, 0, DATEADD(YEAR, -1, GETDATE())) + 1, 0)),
                'Last Day of Previous Year'
    UNION ALL
    SELECT      DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0),
                'First Day of Current Year'
    UNION ALL
    SELECT      DATEADD(MILLISECOND, -3,
                DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0)),
                'Last Day of Current Year'
    UNION ALL
    SELECT      DATEADD(YEAR, DATEDIFF(YEAR, 0,
                DATEADD(YEAR,1,GETDATE())), 0),
                'First Day of Next Year'
    UNION ALL
    SELECT      DATEADD(MILLISECOND, -3,
                DATEADD(YEAR, DATEDIFF(YEAR, 0,
                DATEADD(YEAR, 1, GETDATE())) + 1, 0)),
                'Last Day of Next Year'

    Result Set:

    ———————– ————————–
    2010-01-01 00:00:00.000 First Day of Previous Year
    2010-12-31 23:59:59.997 Last Day of Previous Year
    2011-01-01 00:00:00.000 First Day of Current Year
    2011-12-31 23:59:59.997 Last Day of Current Year
    2012-01-01 00:00:00.000 First Day of Next Year
    2012-12-31 23:59:59.997 Last Day of Next Year

    (6 row(s) affected)

    These can be generalized as:

    – © 2011 – Vishal (http://SqlAndMe.com)

    DECLARE @TRAVELYEARS INT = -1
    SELECT DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, @TRAVELYEARS ,GETDATE())), 0), 'First Day of Year'
    UNION ALL
    SELECT DATEADD(MILLISECOND, -3, DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, @TRAVELYEARS, GETDATE())) + 1, 0)), 'Last Day of Year'
    
    SET @TRAVELYEARS = 1
    SELECT DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, @TRAVELYEARS ,GETDATE())), 0), 'First Day of Year'
    UNION ALL
    SELECT DATEADD(MILLISECOND, -3, DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, @TRAVELYEARS, GETDATE())) + 1, 0)), 'Last Day of Year'

    Result Set:

    ———————– ———————-
    2010-01-01 00:00:00.000 First Day of Next Year
    2010-12-31 23:59:59.997 Last Day of Next Year

    (2 row(s) affected)


    ———————– ———————-
    2012-01-01 00:00:00.000 First Day of Next Year
    2012-12-31 23:59:59.997 Last Day of Next Year

    (2 row(s) affected)

    Hope This Helps!

  • 相关阅读:
    CF Round 594
    [转载]CSP-J/S 第一轮知识点选讲
    10.17 模拟赛
    10.16 模拟赛
    10.15模拟赛
    10.14模拟赛
    10.12 模拟赛
    Peaks Gym 100365H
    手写Bitset优化
    Sums gym100753M
  • 原文地址:https://www.cnblogs.com/taoqianbao/p/2835384.html
Copyright © 2020-2023  润新知