I need to write a function that rounds time in one column to start at its original hour (ex: 23:33:00.0000000 would be 23:00) and time in another column to round up to the next hour (ex: 23:33:00.0000000 would be 24:00) and then insert these new values into new columns. I found this function on Stack Overflow at How to Round a Time in T-SQL, but I can’t get the function to run. I keep getting this error message: ‘Msg 156, Level 15, State 1, Procedure RoundTime, Line 11 Incorrect syntax near the keyword ‘SELECT’.’
CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float)
RETURNS datetime
AS
BEGIN
DECLARE @RoundedTime smalldatetime
DECLARE @Multiplier float
SET @Multiplier= 24.0/@RoundTo
SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier
RETURN @RoundedTime
END
SELECT [dbo].[RoundTime] ('23:33',0.0)
I’ve also tried running it with SELECT dbo.roundtime(’23:33′,0.0) and still no joy.
So I was hoping to try and figure out how to round the time via getting this function to run, but I can’t even run it. And I don’t know the best way to approach getting the hour to round back to its earliest point anyway. Would I just need to extract the hour from the timestamp and then do my insertion of that hour into its new column? Or is there a way to convert it on the fly and then insert it into a new column? I’m using Sql Server 2008.
The function has to exist before you can reference it. Add a GO after the function declaration to separate the creation from the usage.