Get a datetime from year, day of the year and hour in SQL Server 2008 R2

别来无恙 提交于 2019-12-22 04:33:31

问题


I have a table in a Microsft SQL Server 2008 R2, which came from an outside source. The columns of the are as follows: ID, Year, DAY, HOUR & Value, where DAY contains the day of the year (from 1 to 366) and HOUR represents the hour of the day (from 0 to 23).

I wish to create a new datetime column and populate it with the dateTime created from the data in Year, DAY & HOUR columns.

What SQL function should I use to create the DateTime from its parts?

SQL Server 2012 has DATETIMEFROMPARTS, but there is no equivalent function for SQL Server 2008 R2


回答1:


declare @Year int = 2003
declare @Day int = 100
declare @Hour int = 13

select dateadd(hour, @Hour, dateadd(dayofyear, @Day - 1, dateadd(year, @Year - 1900, 0)))



回答2:


You could use the following instead:

DECLARE @day int, @month int, @year int
SELECT @day = 4, @month = 3, @year = 2011

SELECT dateadd(mm, (@year - 1900) * 12 + @month - 1 , @day - 1)

That will give you your date (though it is true that SQL 2012 gets it right, finally!)

To use it when you have year, day of the year and hour of the day, use the following:

declare @year int, @dayofyear int, @hourofday int
select @year = 2013, @dayofyear = 120, @hourofday = 12

select dateadd(hh, @hourofday, dateadd(yy, @year - 1900, dateadd(dd, @dayofyear - 1, 0)))



回答3:


Created that for myself and thought it would be a good place to share - it is based on the sample by Mikael Eriksson.

CREATE FUNCTION [dbo].[DATETIME2FROMPARTS](
    @year int,
    @month int,
    @day int,
    @hour int,
    @minute int,
    @second int,
    @fractions int,
    @precision int)
RETURNS datetime2(7)
AS
BEGIN
    RETURN
        DATEADD(NANOSECOND, POWER(10, 9-@precision)*@fractions, 
        DATEADD(SECOND, @second, 
        DATEADD(MINUTE, @minute, 
        DATEADD(HOUR, @hour, 
        DATEADD(DAY, @day-1, 
        DATEADD(MONTH, @month-1, 
        DATEADD(YEAR, @year-1900, 
        CAST(CAST(0 AS datetime) AS datetime2(7)))))))));
END



回答4:


Here's an alternative solution:

create table yourtable (yr int, dy int, hr int);
insert into yourtable values (2013,100,5);
insert into yourtable values (2013,1,1);

select dateadd(hour,hr,dateadd(month, (yr - 1900) * 12 , dy - 1))
from yourtable

The concept is add the hours to the date, using the year as (year - 1900) * 12 as the month, beginning with the number of days.



来源:https://stackoverflow.com/questions/16298624/get-a-datetime-from-year-day-of-the-year-and-hour-in-sql-server-2008-r2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!