robinson.netdevelop - Monday, December 18, 2017 9:14 AM
Just a couple of recommendations...
First, avoid using VARCHAR(MAX) for returns that will never be more than just 18 characters. It'll help with memory requirements and make your scalar function a touch faster.
Second, I personally don't like the use of "Hungarian Notation" to include the object type in the name of the object. It's normally not necessary but I also understand if you have to follow some company spec that requires you to do so.
Third, you should name variables either for what the actually contain or what they'll be used for instead of generalizing them as just Date1 and Date2 and then having to add comments to let everyone know what they are.
Last but not least, scalar functions like this ten to be about 7 times slower than necessary. There is another method, which will be covered in the second bit of code below. First, here's how I'd write your scalar function if I had to follow a "Hungarian Notation" naming convention. It's similar to what other people have done on this thread but has a much broader range (1 second less than 10,000 years) and it handles problems like the one Scott pointed out.
CREATE FUNCTION dbo.ufn_DifferenceBetweenDates
/**********************************************************************************************************************
Purpose:
Given two dates/times, return the formatted span of time represented by the two dates in the form of #d hh:mi:ss to a
max of 18 characters where "#" is the number of days and will be some value from -2958463 thru 2958463.
-----------------------------------------------------------------------------------------------------------------------
Usage Examples:
--===== Inputs in ascending temporal order left to right.
SELECT dbo.ufn_DifferenceBetweenDates('2017-10-01 01:46:01', '2017-10-17 10:45:00');
Returns: 16d 08:58:59
--===== Inputs in descending temporal order left to right.
SELECT dbo.ufn_DifferenceBetweenDates('2017-10-17 10:45:00','2017-10-01 01:46:01');
Returns: -16d 08:58:59
-----------------------------------------------------------------------------------------------------------------------
1. Note that this is a Scalar function and will be ~7 times slower than an iTVF (Inline Table Value Function).
2. Note that the maximum span that can be returned by this function is 1 second less than 10,000 years of days
or 2958463d 23:59:59 or -2958463d 23:59:59.
3. RETURN type is VARCHAR(18)
4. This function works in all versions of SQL Server from 2000 to current.
-----------------------------------------------------------------------------------------------------------------------
Revision History:
Rev 00 - 22 Dec 2017 - Jeff Moden
- Inital creation and unit test.
- Ref: https://www.sqlservercentral.com/Forums/FindPost1913258.aspx
**********************************************************************************************************************/
--===== Declare the I/O for this scalar function.
(
@StartDT DATETIME
,@EndDT DATETIME
)
RETURNS VARCHAR(18)
AS
BEGIN
RETURN CASE --Calculate and format the span according to the given format depending on the direction of the inputs.
WHEN @StartDT <= @EndDT
THEN CONVERT(VARCHAR(8), DATEDIFF(dd,0,@EndDT-@StartDT)) +'d ' + CONVERT(CHAR(8),@EndDT-@StartDT,108)
ELSE CONVERT(VARCHAR(8),-DATEDIFF(dd,0,@StartDT-@EndDT)) +'d ' + CONVERT(CHAR(8),@StartDT-@EndDT,108)
END
;
END
;
GO
Last but not least, Scalar functions are ~7 times slower than an "iSF" or "Inline Scalar Value Function", which don't currently exist in SQL Server. We can, however, fake it using a "single cell" iTVF or "Inline Table Value Function". It needs to be called in a slightly different fashion but it's well worth it for performance. Here's the code as I would write it without "Hungarian Notation" and includes different usage examples.
CREATE FUNCTION dbo.DifferenceBetweenDates
/**********************************************************************************************************************
Purpose:
Given two dates/times in the correct left to right order, return a formatted period represented by the two dates in
the form of #d hh:mi:ss (or -#d hh:mi:ss) to a max of 18 characters where "#" will be some value from -2958463 thru
2958463, which is only 1 day short of a day-span of 10,000 years.
-----------------------------------------------------------------------------------------------------------------------
Usage Examples:
--===== Basic Syntax for Single Period
SELECT Span FROM dbo.DifferenceBetweenDates(@StartDT,@EndDT)
;
--===== Basic Syntax for Multiple Rows from a Table.
SELECT ca.Span
,st.SomeColumns
FROM dbo.SomeTable st
CROSS APPLY dbo.DifferenceBetweenDates(st.StartDT,st.EndDT) ca
;
-----------------------------------------------------------------------------------------------------------------------
Developer notes:
1. This is a high performance iTVF (inline Table Valued Function), which executes about 7 times faster than the
equivalent Scalar function. Please see the following URL for more information on this subject.
http://www.sqlservercentral.com/articles/T-SQL/91724/
2. Note that the maximum span that can be returned by this function is 1 second less than 10,000 years of days
or 2958463d 23:59:59 (when @StartDate <= @EndDate) or -2958463d 23:59:59 (when @StartDate > @EndDate).
3. RETURN type is VARCHAR(18)
4. This function works in all versions of SQL Server from 2000 to current.
-----------------------------------------------------------------------------------------------------------------------
Revision History:
Rev 00 - 22 Dec 2017 - Jeff Moden
- Inital creation and unit test.
- Ref: https://www.sqlservercentral.com/Forums/FindPost1913258.aspx
**********************************************************************************************************************/
--===== Define the I/O for this function
(
@StartDT DATETIME
,@EndDT DATETIME
)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== Calculate format, and return the period as a "single cell" table depending on the direction of the inputs.
SELECT Span = CASE
WHEN @StartDT <= @EndDT
THEN CONVERT(VARCHAR(8), DATEDIFF(dd,0,@EndDT-@StartDT)) +'d ' + CONVERT(CHAR(8),@EndDT-@StartDT,108)
ELSE CONVERT(VARCHAR(8),-DATEDIFF(dd,0,@StartDT-@EndDT)) +'d ' + CONVERT(CHAR(8),@StartDT-@EndDT,108)
END
;
GO
--Jeff Moden
Change is inevitable... Change for the better is not.