I need to set just the hour of a datetime to a certain value. I know I can add it the difference to the desired value, or create a new datetime with parts from the original one, but isn’t there a cleaner way? Something like:
declare @d datetime = '09/08/2012 09:14:55'
set @d = SETDATEPARTORSOMETHINGLIKETHAT (hour, @d, 23)
Thanks a lot.
Result:
(And yes, this will work if the @TargetHour is less than the current hour, e.g. 5 or 7.)
I’d be very careful though about using ambiguous and error-prone formats like m/d/y. Case in point: I don’t even know if you meant September 8th or August 9th, and SQL Server isn’t going to know either – it needs to use regional settings etc. to figure it out, and if you give your code to someone with different settings, it will generate an error or, even worse, accept the wrong date silently. You should use: