So first of all I was thinking about the approach to change the orbit around the sun to correct it to exact 360 days a year. But this would probably ends in some bad side effects...
As I want the exact amount I write this (see below) and it seems to work as intended for my needs. I share this for discussions, improvements and to share if anyone need this, too.
DECLARE @start datetime;
DECLARE @end datetime;
DECLARE @current datetime;
DECLARE @year int
DECLARE @month int
DECLARE @days int;
DECLARE @daytmp int;
-- note start date earliest: 1/1/1753
SET @start = CAST('28.02.1753' AS datetime)
SET @end = GETDATE() --CAST('31.12.2016' AS datetime)
SET @current = @start
SET @days = (SELECT DATEDIFF(day, @start, @end))
SET @year = 0;
WHILE @days>365
BEGIN
SET @days = @days - (SELECT DATEDIFF(day, @current, DATEADD(YEAR, 1, @current)))
SET @current = DATEADD(YEAR, 1, @current)
SET @year = @year + 1
END
SET @month = 0;
SET @daytmp = @days
WHILE @daytmp>28
BEGIN
SET @daytmp = @days - (SELECT DATEDIFF(day, @current, DATEADD(MONTH, 1, @current)))
IF (@daytmp>0) BEGIN
SET @days = @daytmp
SET @current = DATEADD(MONTH, 1, @current)
SET @month = @month + 1
END
END
PRINT @year
PRINT @month
PRINT @days
I moved this in to table function that returns 3 values with position 1,2,3 so I can use it inside select statements.
CREATE FUNCTION dbo.sf_GetYearMonthDayFromRange(@start datetime, @end datetime)
RETURNS @result TABLE ([value] int, [position] int)
AS
BEGIN
DECLARE @current datetime;
DECLARE @year int
DECLARE @month int
DECLARE @days int;
DECLARE @daytmp int;
SET @current = @start
SET @days = (SELECT DATEDIFF(day, @start, @end))
SET @year = 0;
WHILE @days>365
BEGIN
SET @days = @days - (SELECT DATEDIFF(day, @current, DATEADD(YEAR, 1, @current)))
SET @current = DATEADD(YEAR, 1, @current)
SET @year = @year + 1
END
SET @month = 0;
SET @daytmp = @days
WHILE @daytmp>28
BEGIN
SET @daytmp = @days - (SELECT DATEDIFF(day, @current, DATEADD(MONTH, 1, @current)))
IF (@daytmp>0) BEGIN
SET @days = @daytmp
SET @current = DATEADD(MONTH, 1, @current)
SET @month = @month + 1
END
END
INSERT INTO @result SELECT @year, 1
INSERT INTO @result SELECT @month, 2
INSERT INTO @result SELECT @days, 3
RETURN
END