Convert day of year to datetime in SQL Server

后端 未结 2 427
温柔的废话
温柔的废话 2021-01-20 04:54

In a database table (SQL Server 2012), I have dates saved in the yyyyxxx format, where xxx is the day of the year. For example 2015-08-11

2条回答
  •  星月不相逢
    2021-01-20 05:21

    Get the Year part, convert to datetime + add days

    DECLARE @var NVARCHAR(100) = '2015223';
    
    SELECT CAST(LEFT(@var, 4) AS DATETIME) +  CAST(RIGHT(@var, 3) AS INT) - 1;
    

    Or:

    DECLARE @var NVARCHAR(100) = '2015223';
    
    SELECT DATEADD(dd,CAST(RIGHT(@var, 3) AS INT)-1, CAST(LEFT(@var, 4) AS DATETIME))
    

    Or if yyyyxxx is INT:

    DECLARE @var INT = 2015223;
    
    SELECT DATEADD(dd,(@var%1000)-1, CAST(CAST((@var/1000) AS NVARCHAR(100)) 
                   AS DATETIME));
    

    LiveDemo

提交回复
热议问题