Selecting only 'month-day time' from Datetime field in SQL (server 2012)

时间:2019-01-07 13:08:11

标签: sql sql-server datetime sql-server-2012

I'm looking at changing a specific date to a different date in a case statement, however, I only want it to apply to a day, month and time.

For example, I want to get the case statement to change any date which falls on 31/12 @ 23:59:00 to 01/01 @ 00:00:00 but unless I write the case to include each year for the next 40 years to cover myself, I've not been able to resolve this.

I am writing this from the UK with date format being dd/mm/yyyy (above example is 31st December and 1st January).

The format of the datetime field in the database is 'datetime': 2019-07-01 13:14:47).

2 个答案:

答案 0 :(得分:2)

我无法确定您是否希望返回类型为datedatetime。如果是date,则可以执行以下操作:

(case when year(dateadd(minute, 1, datecol)) <> year(datecol)
      then datefromparts(year(datecol) + 1, month(datecol), day(datecol))
      else cast(datecol as date)
 end)

假设datetime已经是datecol,则datetime的逻辑类似:

(case when year(dateadd(minute, 1, datecol)) <> year(datecol)
      then datefromparts(year(datecol) + 1, month(datecol), day(datecol))
      else datecol
 end)

答案 1 :(得分:2)

If I understand correctly you want to round the dates inside last minute of year into the next year. You can do this:

SELECT datecol, CASE
    WHEN MONTH(datecol) = 12 AND DAY(datecol) = 31 AND CAST(datecol AS TIME(3)) >= '23:59:00' THEN CAST(DATEADD(MINUTE, 1, datecol) AS DATE)
    ELSE datecol
END
FROM (VALUES
    (CAST('2018-12-31 23:58:59.997' AS DATETIME)),
    (CAST('2018-12-31 23:59:00.000' AS DATETIME)),
    (CAST('2018-12-31 23:59:59.997' AS DATETIME)),
    (CAST('2019-01-01 00:00:00.000' AS DATETIME))
) AS v(datecol)

Result:

2018-12-31 23:58:59.997    2018-12-31 23:58:59.997
2018-12-31 23:59:00.000    2019-01-01 00:00:00.000
2018-12-31 23:59:59.997    2019-01-01 00:00:00.000
2019-01-01 00:00:00.000    2019-01-01 00:00:00.000