问题
I have a few date time functions within my database, but I need to add one that takes the time portion of a datetime field and then converts the time into minutes
I have a function that get the minutes between two times, but not just the minutes of a single time.
ALTER FUNCTION [dbo].[fn_MinutesBetween]
( @fStart datetime, @fEnd datetime )
RETURNS int
AS
BEGIN
RETURN DateDiff(minute, @fStart, @fEnd)
and another one that gets just the time portion
ALTER function [dbo].[fn_ReturnTimeOnly]
(@DateTime smallDateTime)
returns nvarchar(50)
as
begin
Return substring(cast(@DateTime as varchar),12,len(@DateTime))
end
How can I just get the minutes of the time. Like 1:00 am would be 60, 2:00 am would be 120 12:00 pm would be 720 etc.
Thanks
回答1:
I was given a link in comments to datetime to totalminute and used that to come up with a solution.
ALTER FUNCTION [dbo].[fn_ReturnMinutesOnly]
( @dt smalldatetime )
RETURNS int
AS
BEGIN
RETURN DATEDIFF(MINUTE, DATEADD(DAY, DATEDIFF(DAY, 0, @dt), 0), @dt)
END
回答2:
Get the number of hours, cast to int, multiply by 60, get the number of mins, cast to int, add these two.
ALTER function [dbo].[fn_ReturnMinutesOnly]
(@DateTime smallDateTime)
returns INT
as
begin
Return
cast(substring(cast(@DateTime as varchar),13,2) as INT) * 60 +
cast(substring(cast(@DateTime as varchar),16,2) as INT)
end
回答3:
Casting to string is expensive (I talk about the opposite scenario here, but the concept is the same). Try this instead:
DECLARE @DateTime DATETIME;
SET @DateTime = GETDATE();
SELECT DATEDIFF(MINUTE, DATEDIFF(DAY, 0, @DateTime), @DateTime);
In your function, this would be:
ALTER function [dbo].[fn_ReturnTimeOnly]
(@DateTime smallDateTime)
returns INT
as
begin
Return (SELECT DATEDIFF(MINUTE, DATEDIFF(DAY, 0, @DateTime), @DateTime));
end
来源:https://stackoverflow.com/questions/15980219/sql-server-2005-convert-time-to-minutes