Frage

I'm trying to do something like below (I've simplified the problem, to try and solve this individual part).

PRINT DATEADD(week, 0.2,  GETDATE())

Which I realise will not work due to the number parameter of dateadd is truncated to an int.

I'm trying to come up with a way of converting 0.2 to a number of hours and then being able to use something like (I'm ok with it being as accurate to the hour).

PRINT DATEADD(hour, X,  GETDATE())

Any ideas how to get started? I'm finding it tricky to find anything to get a decimal representation of one datepart in another datepart.

It's got to be a set based query for performance.

In theory I've got to make it so decimal years can be used as well, but I'll come to that as a seperate problem...

War es hilfreich?

Lösung

1 week = 7 days = 168 hours = 10080 minutes

0.2 weeks = 2016 minutes

PRINT DATEADD(minute, 2016, GETDATE())

To get this to work for years, you could write a User Defined Function where you can input a decimal of years, and then this is multiplied for minutes, and run DATEADD using minutes

Andere Tipps

This is what I came up with incase it comes in useful for anyone. Curt helped me open my eyes to that my problem was infact not as complex as I first thought. I've marked Curt's answer as the solution, but here is some sample code. Notably the 10% wasn't in my original question but it demonstrates why I needed decimals.

DECLARE @DatePart int,
        @DateNumber int;

SET @DatePart = 1
SET @DateNumber = 1                         

PRINT
    DATEADD(
                hour,
                CEILING
                (           
                    CASE @DatePart
                        WHEN 1 THEN @DateNumber * 24.000000 --days
                        WHEN 2 THEN @DateNumber * 168.000000 --weeks
                        WHEN 3 THEN @DateNumber * 730.484398 --months
                        WHEN 4 THEN @DateNumber * 8765.81277 --years
                    END / 100.000000 * 10.000000
                ),
                GETDATE()
            ) 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top