﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2008 / T-SQL (SS2K8)  / Time as a high precision difference of dates / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Sat, 18 May 2013 09:07:27 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Updated my SQLCLR function to produce the results needed in this thread:[code="plain"][font="Courier New"][size="2"][color="black"]&amp;#160;&amp;#160;&amp;#160;&amp;#160;[/color][color="blue"]public static [/color][color="black"]TimeSpan GetIntervalAsTime[/color][color="gray"]([/color][color="black"]DateTime Start[/color][color="gray"], [/color][color="black"]DateTime End[/color][color="gray"])&amp;#160;&amp;#160;&amp;#160;&amp;#160;[/color][color="black"]{&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;[/color][color="blue"]return&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;[/color][color="gray"]([/color][color="black"]Start [/color][color="gray"]&amp;lt;= [/color][color="black"]End[/color][color="gray"]) ?&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;[/color][color="black"]End.Subtract[/color][color="gray"]([/color][color="black"]Start[/color][color="gray"]) :&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;[/color][color="black"]End.AddDays[/color][color="gray"]([/color][color="black"]1[/color][color="gray"])[/color][color="black"].Subtract[/color][color="gray"]([/color][color="black"]Start[/color][color="gray"]);&amp;#160;&amp;#160;&amp;#160;&amp;#160;[/color][color="black"]}[/color][/size][/font][/code]Test data:[code="sql"]With MyCTE (ID, aTime, bTime)AS(	SELECT 1, CONVERT(datetime2,'1900-01-01 00:08:00.0000001'), CONVERT(datetime2,'1900-01-01 00:09:18.361') 	UNION ALL SELECT  2, '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705'	UNION ALL SELECT  3, '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001'	UNION ALL SELECT  4, '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'	UNION ALL SELECT  5, '1900-01-01 00:00:00.0000001', '1900-01-01 00:00:00.0000002'	UNION ALL SELECT  6, '1900-01-01 00:00:00.0000002', '1900-01-01 00:00:00.0000001'	UNION ALL SELECT  7, '1900-01-01 00:10:00.0000001', '1900-01-01 00:00:00.0000002'	UNION ALL SELECT  8, '1900-01-01 00:10:01.9999988', '1900-01-01 00:10:00.0000022'	UNION ALL SELECT  9, '1900-01-01 00:10:00.9999998', '1900-01-01 00:10:01.0000001'	UNION ALL SELECT 10, '1900-01-01 00:10:00.0000023', '1900-01-01 00:10:01.0000022'	UNION ALL SELECT 11, '1900-01-01 00:10:00.0000022', '1900-01-01 00:10:01.0000022'	UNION ALL SELECT 12, '1900-01-01 00:10:00.0000021', '1900-01-01 00:10:01.0000022')SELECT     TimeDiff = dbo.GetIntervalAsTime (aTime, bTime)FROM MyCTE;[/code]Updated assembly and function definition:[code="sql"]CREATE ASSEMBLY IntervalsFROM 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C010300B59A4A500000000000000000E00002210B0108000008000000060000000000007E260000002000000040000000004000002000000002000004000000000000000400000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000282600005300000000400000A802000000000000000000000000000000000000006000000C0000008C2500001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E7465787400000084060000002000000008000000020000000000000000000000000000200000602E72737263000000A80200000040000000040000000A0000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000000E000000000000000000000000000040000042000000000000000000000000000000006026000000000000480000000200050090200000FC0400000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000133003002C000000010000110203280500000A2D1A0F0123000000000000F03F280600000A0A120002280700000A2A0F0102280700000A2A1E02280800000A2A42534A4201000100000000000C00000076322E302E35303732370000000005006C00000048010000237E0000B40100007801000023537472696E6773000000002C03000008000000235553003403000010000000234755494400000044030000B801000023426C6F620000000000000002000001471502000900000000FA2533001600000100000008000000020000000200000002000000080000000400000001000000010000000200000000000A0001000000000006003D00360006004400360006004D00360006008B00780013009F0000000600CE00AE000600EE00AE000A003D01220100000000010000000000010001000100100018000000050001000100502000000000960056000A0001008820000000008618680013000300000001006E00000002007400210068001700310068001D00390068001300410068001300190052016A0119006501720119006D0178010900680013002000230022002E000B0084012E0013008D012E001B0096017F010480000000000000000000000000000000000C01000002000000000000000000000001002D000000000002000000000000000000000001001601000000000000003C4D6F64756C653E00496E74657276616C732E646C6C0055736572446566696E656446756E6374696F6E73006D73636F726C69620053797374656D004F626A6563740054696D655370616E004461746554696D6500476574496E74657276616C417354696D65002E63746F7200537461727400456E640053797374656D2E446961676E6F73746963730044656275676761626C6541747472696275746500446562756767696E674D6F6465730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C69747941747472696275746500496E74657276616C730053797374656D2E44617461004D6963726F736F66742E53716C5365727665722E5365727665720053716C46756E6374696F6E417474726962757465006F705F4C6573735468616E4F72457175616C004164644461797300537562747261637400000000032000000000003D49F20ED1D67D44ACCAD7654574023D0008B77A5C561934E0890800021109110D110D0320000105200101111504200101088146010004005455794D6963726F736F66742E53716C5365727665722E5365727665722E446174614163636573734B696E642C2053797374656D2E446174612C2056657273696F6E3D322E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038390A446174614163636573730000000054557F4D6963726F736F66742E53716C5365727665722E5365727665722E53797374656D446174614163636573734B696E642C2053797374656D2E446174612C2056657273696F6E3D322E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038391053797374656D446174614163636573730000000054020F497344657465726D696E6973746963015402094973507265636973650107000202110D110D052001110D0D0620011109110D040701110D0801000200000000000801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F77730100000000000000B59A4A50000000000200000080000000A8250000A807000052534453059586A87E0DEA40A2186106E3FD4C5B07000000633A5C55736572735C5061756C2057686974655C446F63756D656E74735C56697375616C2053747564696F20323031305C50726F6A656374735C4461746162617365325C4461746162617365325C6F626A5C52656C656173655C496E74657276616C732E706462005026000000000000000000006E2600000020000000000000000000000000000000000000000000006026000000000000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF25002040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001001000000018000080000000000000000000000000000001000100000030000080000000000000000000000000000001000000000048000000584000004C02000000000000000000004C0234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100000000000000000000000000000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004AC010000010053007400720069006E006700460069006C00650049006E0066006F0000008801000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000030002E0030002E0030002E00300000003C000E00010049006E007400650072006E0061006C004E0061006D006500000049006E00740065007200760061006C0073002E0064006C006C0000002800020001004C006500670061006C0043006F00700079007200690067006800740000002000000044000E0001004F0072006900670069006E0061006C00460069006C0065006E0061006D006500000049006E00740065007200760061006C0073002E0064006C006C000000340008000100500072006F006400750063007400560065007200730069006F006E00000030002E0030002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000030002E0030002E0030002E0030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000C000000803600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000WITH PERMISSION_SET = SAFE;GOCREATE FUNCTION dbo.GetIntervalAsTime(    @Start  datetime2(7),     @End    datetime2(7))RETURNS time(7)AS EXTERNAL NAME Intervals.UserDefinedFunctions.GetIntervalAsTime;[/code]</description><pubDate>Fri, 07 Sep 2012 18:31:32 GMT</pubDate><dc:creator>Paul White</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]ScottPletcher (9/7/2012)[/b][hr][quote]    TimeResult1 = -- ChrisR (5 date functions, 2 datatype conversions)     TimeResult2 = -- ChrisM (5 date functions, 2 datatype conversions)     TimeDiff = -- ScottP (8 date functions, 3 datatype conversions)    TimeDiff = -- Steven W (5 date functions, 10 datatype conversions) [/quote]These totals aren't quite accurate.My code uses [u]only columns native to the table[/u].All other code [u]use derived column that require pre-computing[/u].[/quote]Looking at the execution plans for:[code="sql"]With MyCTE (ID, aTime, bTime)AS(	SELECT 1, CONVERT(datetime2,'1900-01-01 00:08:00.0000001'), CONVERT(datetime2,'1900-01-01 00:09:18.361') 	UNION ALL SELECT  2, '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705'	UNION ALL SELECT  3, '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001'	UNION ALL SELECT  4, '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'	UNION ALL SELECT  5, '1900-01-01 00:00:00.0000001', '1900-01-01 00:00:00.0000002'	UNION ALL SELECT  6, '1900-01-01 00:00:00.0000002', '1900-01-01 00:00:00.0000001'	UNION ALL SELECT  7, '1900-01-01 00:10:00.0000001', '1900-01-01 00:00:00.0000002'	UNION ALL SELECT  8, '1900-01-01 00:10:01.9999988', '1900-01-01 00:10:00.0000022'	UNION ALL SELECT  9, '1900-01-01 00:10:00.9999998', '1900-01-01 00:10:01.0000001'	UNION ALL SELECT 10, '1900-01-01 00:10:00.0000023', '1900-01-01 00:10:01.0000022'	UNION ALL SELECT 11, '1900-01-01 00:10:00.0000022', '1900-01-01 00:10:01.0000022'	UNION ALL SELECT 12, '1900-01-01 00:10:00.0000021', '1900-01-01 00:10:01.0000022')SELECT     aTime,     bTime,    	TimeDiff = -- ScottP		CONVERT(varchar(8), DATEADD(SECOND, DATEDIFF(SECOND, aTime  , bTime)			- CASE WHEN DATEPART(NANOSECOND, aTime) &amp;gt; DATEPART(NANOSECOND, bTime) THEN 1 ELSE 0 END, 0), 108) +		'.' + RIGHT(REPLICATE('0', 7) +		CAST(((CASE WHEN DATEPART(NANOSECOND, aTime) &amp;gt; DATEPART(NANOSECOND, bTime) THEN 1000000000 ELSE 0 END +		DATEPART(NANOSECOND, bTime) - DATEPART(NANOSECOND, aTime)) / 100) AS varchar(7)), 7)  FROM MyCTE;With MyCTE (ID, aTime, bTime)AS(	SELECT 1, CONVERT(datetime2,'1900-01-01 00:08:00.0000001'), CONVERT(datetime2,'1900-01-01 00:09:18.361') 	UNION ALL SELECT  2, '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705'	UNION ALL SELECT  3, '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001'	UNION ALL SELECT  4, '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'	UNION ALL SELECT  5, '1900-01-01 00:00:00.0000001', '1900-01-01 00:00:00.0000002'	UNION ALL SELECT  6, '1900-01-01 00:00:00.0000002', '1900-01-01 00:00:00.0000001'	UNION ALL SELECT  7, '1900-01-01 00:10:00.0000001', '1900-01-01 00:00:00.0000002'	UNION ALL SELECT  8, '1900-01-01 00:10:01.9999988', '1900-01-01 00:10:00.0000022'	UNION ALL SELECT  9, '1900-01-01 00:10:00.9999998', '1900-01-01 00:10:01.0000001'	UNION ALL SELECT 10, '1900-01-01 00:10:00.0000023', '1900-01-01 00:10:01.0000022'	UNION ALL SELECT 11, '1900-01-01 00:10:00.0000022', '1900-01-01 00:10:01.0000022'	UNION ALL SELECT 12, '1900-01-01 00:10:00.0000021', '1900-01-01 00:10:01.0000022')SELECT     aTime,     bTime,    	TimeResult1 = -- ChrisM 		CAST(DATEADD(ns,              (CASE WHEN aTime &amp;lt; bTime 					THEN DATEPART(ns,bTime)-DATEPART(ns,aTime)					ELSE DATEPART(ns,aTime)-DATEPART(ns,bTime) END),                   DATEADD(ss,                     ABS(DATEDIFF(ss,aTime,bTime)),                    CAST('1900-01-01 00:00' AS datetime2))              ) AS TIME(7))From MyCTECROSS APPLY (	SELECT         Sec = (DATEDIFF(second, aTime, btime)),        NanoSec = (DATEPART(ns,btime)-DATEPART(ns,atime)),        StartTime = CASE WHEN aTime &amp;lt; bTime THEN aTime ELSE bTime END,         EndTime = CASE WHEN aTime &amp;lt; bTime THEN bTime ELSE aTime END       ) x;[/code]...the Compute Scalars contain:ChrisM : 1 conversion, 6 functionsScottP: 2 conversions, 8 functionsNote: The ChrisM code returns a time(7) whereas ScottP returns varchar(8)[code="plain"]-- ScottP[Expr1043] = Scalar Operator(    CONVERT(varchar(8),        dateadd(second,        datediff(second,            CONVERT_IMPLICIT(datetimeoffset(7),[Union1037],0),            CONVERT_IMPLICIT(datetimeoffset(7),[Union1038],0))-            CASE WHEN         datepart(nanosecond,[Union1037])&amp;gt;        datepart(nanosecond,[Union1038])             THEN (1) ELSE (0) END,'1900-01-01 00:00:00.000'),108)+'.'+ right('0000000'+    CONVERT(varchar(7),(            CASE WHEN         datepart(nanosecond,[Union1037])&amp;gt;        datepart(nanosecond,[Union1038])             THEN (1000000000) ELSE (0) END+        datepart(nanosecond,[Union1038])-        datepart(nanosecond,[Union1037]))/(100),0),(7)))[/code][code="plain"]-- ChrisM[Expr1043] = Scalar Operator(    CONVERT(time(7),        dateadd(nanosecond,            CASE WHEN [Union1037]&amp;lt;[Union1038] THEN         datepart(nanosecond,[Union1038])-        datepart(nanosecond,[Union1037])             ELSE         datepart(nanosecond,[Union1037])-        datepart(nanosecond,[Union1038]) END,        dateadd(second,abs(datediff(second,            CONVERT_IMPLICIT(datetimeoffset(7),[Union1037],0),            CONVERT_IMPLICIT(datetimeoffset(7),[Union1038],0))),'1900-01-01 00:00:00.0000000')),0))[/code]</description><pubDate>Fri, 07 Sep 2012 18:19:47 GMT</pubDate><dc:creator>Paul White</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote]    TimeResult1 = -- ChrisR (5 date functions, 2 datatype conversions)     TimeResult2 = -- ChrisM (5 date functions, 2 datatype conversions)     TimeDiff = -- ScottP (8 date functions, 3 datatype conversions)    TimeDiff = -- Steven W (5 date functions, 10 datatype conversions) [/quote]These totals aren't quite accurate.My code uses [u]only columns native to the table[/u].All other code [u]use derived column that require pre-computing[/u].</description><pubDate>Fri, 07 Sep 2012 12:00:52 GMT</pubDate><dc:creator>ScottPletcher</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]bmahf (9/6/2012)[/b][hr]So it turns out that each of these solutions is missing something, it's either the fraction part sometimes comes out incorrect, because it wasn't adjusted as I was doing in my case statement, or the seconds were not adjusted, which I also did in the other case statement I sent.  I also found that the case where I adjusted the fraction part because it was negative still had another issue, which was that it was never adjusted for position.So since this is for a one-time converter, which doesn't have to be optimized to the extreme, I rewrote my version, and made it into a function, and I call that function inside my select.  My version now looks like this, and I haven't found any problems with it yet:But, I must say it is interested to try to figure out the optimized version.  It's just that the possible adjustment and the positioning of the fractional part, and the possible adjustment of the seconds part need to be taken into account.Thanks for all the help.[/quote]Interested to see your new version, Bruce.</description><pubDate>Fri, 07 Sep 2012 02:11:29 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]ScottPletcher (9/6/2012)[/b][hr][quote][b]bmahf (9/6/2012)[/b][hr]So it turns out that each of these solutions is missing something, it's either the fraction part sometimes comes out incorrect, because it wasn't adjusted as I was doing in my case statement, or the seconds were not adjusted, which I also did in the other case statement I sent.  I also found that the case where I adjusted the fraction part because it was negative still had another issue, which was that it was never adjusted for position.So since this is for a one-time converter, which doesn't have to be optimized to the extreme, I rewrote my version, and made it into a function, and I call that function inside my select.  My version now looks like this, and I haven't found any problems with it yet:But, I must say it is interested to try to figure out the optimized version.  It's just that the possible adjustment and the positioning of the fractional part, and the possible adjustment of the seconds part need to be taken into account.Thanks for all the help.[/quote]I don't see those issues with my code, but I too did not do an exhaustive check against all possible values :-) .[/quote]Your code is spot on, Scott, with all the values we've tested so far:[code="sql"];With MyCTE (RowID, aTime, bTime)AS(      SELECT 1, CONVERT(datetime2,'1900-01-01 00:08:00.0000001'), CONVERT(datetime2,'1900-01-01 00:09:18.3610010')       UNION ALL SELECT 2, '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705002'      UNION ALL SELECT 3, '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001'      UNION ALL SELECT 4, '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'      UNION ALL SELECT 5, '1900-01-01 00:00:00.000000111', '1900-01-01 00:00:00.000000222'      UNION ALL SELECT 6, '1900-01-01 00:00:00.000000222', '1900-01-01 00:00:00.000000111'      UNION ALL SELECT 7, '1900-01-01 00:10:00.000000111', '1900-01-01 00:00:00.000000222'      UNION ALL SELECT 8, '1900-01-01 00:10:00.999998811', '1900-01-01 00:10:01.000002222'      UNION ALL SELECT 9, '1900-01-01 00:10:01.999998811', '1900-01-01 00:10:00.000002222'      UNION ALL SELECT 10, '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705'      UNION ALL SELECT 11, '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001'      UNION ALL SELECT 12, '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'      UNION ALL SELECT 13, '1900-01-01 00:00:00.0000001', '1900-01-01 00:00:00.0000002'      UNION ALL SELECT 14, '1900-01-01 00:00:00.0000002', '1900-01-01 00:00:00.0000001'      UNION ALL SELECT 15, '1900-01-01 00:10:00.0000001', '1900-01-01 00:00:00.0000002'      UNION ALL SELECT 16, '1900-01-01 00:10:01.9999988', '1900-01-01 00:10:00.0000022'      UNION ALL SELECT 17, '1900-01-01 00:10:00.9999998', '1900-01-01 00:10:01.0000001'      UNION ALL SELECT 18, '1900-01-01 00:10:00.0000023', '1900-01-01 00:10:01.0000022'      UNION ALL SELECT 19, '1900-01-01 00:10:00.0000022', '1900-01-01 00:10:01.0000022'      UNION ALL SELECT 20, '1900-01-01 00:10:00.0000021', '1900-01-01 00:10:01.0000022'      UNION ALL SELECT 21, '1900-01-01 00:10:00.0000020', '1900-01-01 00:10:01.0000022')SELECT	RowID,      aTime,     bTime,    SimpleProof = CASE WHEN ABS(DATEDIFF(ss,aTime,bTime)) &amp;lt; 11072 		THEN CAST(DATEADD(microsecond,ABS(DATEDIFF(microsecond,aTime, bTime)),CAST('1900' AS DATETIME2)) AS TIME(7))		ELSE CAST(DATEADD(millisecond,ABS(DATEDIFF(millisecond,aTime, bTime)),CAST('1900' AS DATETIME2)) AS TIME(7)) END,        TimeResult1 = -- ChrisR (5 date functions, 2 datatype conversions) 		CAST(			DATEADD(nanosecond,            CASE                 WHEN Sec = 0 THEN ABS(NanoSec)                WHEN Sec &amp;lt; 0 THEN NanoSec * -1                ELSE NanoSec            END,            DATEADD(second,ABS(Sec),CAST('1900-01-01 00:00' AS datetime2))        ) AS TIME(7)),        	TimeResult2 = -- ChrisM (5 date functions, 2 datatype conversions) 		CAST(			DATEADD(ns,(DATEPART(ns,bTime)-DATEPART(ns,aTime)) * (CASE WHEN aTime &amp;lt; bTime THEN 1 ELSE -1 END),     			DATEADD(ss,ABS(DATEDIFF(ss,aTime,bTime)),CAST('1900' AS datetime2))		) AS TIME(7)),	TimeDiff = -- ScottP (8 date functions, 3 datatype conversions)		CAST(			CONVERT(varchar(8), DATEADD(SECOND, DATEDIFF(SECOND, StartTime, EndTime)				- CASE WHEN DATEPART(NANOSECOND, StartTime) &amp;gt; DATEPART(NANOSECOND, EndTime) THEN 1 ELSE 0 END, 0), 108) +			'.' + RIGHT(REPLICATE('0', 7) +			CAST(((CASE WHEN DATEPART(NANOSECOND, StartTime) &amp;gt; DATEPART(NANOSECOND, EndTime) THEN 1000000000 ELSE 0 END +			DATEPART(NANOSECOND, EndTime) - DATEPART(NANOSECOND, StartTime)) / 100) AS varchar(7)), 7)		AS TIME(7)),					TimeDiff = -- Steven W (5 date functions, 10 datatype conversions) 				-- fails with datetime conversion error on rows 3,4,7,9,11,12,15,16,18 				-- returns incorrect result for rows 8 &amp; 17 using starttime &amp; endtime				-- returns incorrect result for rows 6,8,14 &amp; 17 using atime &amp; btime  		CAST(RIGHT('00' + CONVERT(VARCHAR,DATEDIFF(hour,aTime,bTime) % 24),2)			+ ':' + RIGHT('00' + CONVERT(VARCHAR,DATEDIFF(minute,aTime,bTime) % 60),2)			+ ':' + RIGHT('00' + CONVERT(VARCHAR,(DATEDIFF(second,aTime,bTime)) % 60),2)			+ '.' + RIGHT('0000000' + CONVERT(VARCHAR,(CAST((CAST(CAST(DATEPART(nanosecond,EndTime) AS INT) AS DECIMAL(18,8))/100) 				- (CAST(CAST(DATEPART(nanosecond,aTime) AS INT) AS DECIMAL(18,8))/100) AS INT))),7) 		AS TIME)                From (    SELECT		RowID,         Sec = (DATEDIFF(second, aTime, btime)),        NanoSec = (DATEPART(ns,btime)-DATEPART(ns,atime)),        aTime,        bTime,        StartTime = CASE WHEN aTime &amp;lt; bTime THEN aTime ELSE bTime END,         EndTime = CASE WHEN aTime &amp;lt; bTime THEN bTime ELSE aTime END             FROM MyCTE) d--WHERE RowID NOT IN (3,4,7,9,11,12,15,16,18) -- rows which may fail[/code]</description><pubDate>Fri, 07 Sep 2012 02:09:56 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Erland has a Connect request that seems relevant to this discussion:[url]http://connect.microsoft.com/SQLServer/feedback/details/320998/add-datediff-big[/url]</description><pubDate>Thu, 06 Sep 2012 17:53:58 GMT</pubDate><dc:creator>Paul White</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]bmahf (9/6/2012)[/b][hr]So it turns out that each of these solutions is missing something, it's either the fraction part sometimes comes out incorrect, because it wasn't adjusted as I was doing in my case statement, or the seconds were not adjusted, which I also did in the other case statement I sent.  I also found that the case where I adjusted the fraction part because it was negative still had another issue, which was that it was never adjusted for position.So since this is for a one-time converter, which doesn't have to be optimized to the extreme, I rewrote my version, and made it into a function, and I call that function inside my select.  My version now looks like this, and I haven't found any problems with it yet:But, I must say it is interested to try to figure out the optimized version.  It's just that the possible adjustment and the positioning of the fractional part, and the possible adjustment of the seconds part need to be taken into account.Thanks for all the help.[/quote]I don't see those issues with my code, but I too did not do an exhaustive check against all possible values :-) .</description><pubDate>Thu, 06 Sep 2012 15:18:15 GMT</pubDate><dc:creator>ScottPletcher</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Leaving off the day value from my first posting above and casting the result as a TIME datatype works for me. In every scenario I tried even if the end date is earlier than the start date or if the nanosecond part of one is greater/lesser than the other I get a valid result. As for an exhaustive testing against all possible date ranges or for performance I'll leave to others. This was an interesting problem! I have occasion to need date range calculations from time to time (though not at this level of precision) so will add this snippet to my tool box.[code="sql"]DECLARE 	@StartTime DATETIME2(7)	,@EndTime DATETIME2(7)	SET @StartTime = '2012-04-26 13:53:43.0000000'SET @EndTime = '2012-04-26 13:54:44.5448951'--SET @StartTime = '2012-10-01 12:00:00.0130952'--SET @EndTime = '2012-10-01 17:00:04.9845083'--SET @StartTime = '2012-10-01 12:00:00.9845083'--SET @EndTime = '2012-10-01 17:00:04.0130952'--SET @StartTime = '2012-04-26 13:53:43.5448951'--SET @EndTime = '2012-04-26 13:54:44.0000000'SELECT     @StartTime AS stime    ,@EndTime AS etime    ,CAST(RIGHT('00' + CONVERT(VARCHAR,DATEDIFF(hour,@StartTime,@EndTime) % 24),2)        + ':' + RIGHT('00' + CONVERT(VARCHAR,DATEDIFF(minute,@StartTime,@EndTime) % 60),2)        + ':' + RIGHT('00' + CONVERT(VARCHAR,(DATEDIFF(second,@StartTime,@EndTime)) % 60),2)        + '.' + RIGHT('0000000' + CONVERT(VARCHAR,(CAST((CAST(CAST(DATEPART(nanosecond,@EndTime) AS INT) AS DECIMAL(18,8))/100) - (CAST(CAST(DATEPART(nanosecond,@StartTime) AS INT) AS DECIMAL(18,8))/100) AS INT))),7)      AS TIME) AS timediff[/code]</description><pubDate>Thu, 06 Sep 2012 15:12:04 GMT</pubDate><dc:creator>Steven Willis</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>So it turns out that each of these solutions is missing something, it's either the fraction part sometimes comes out incorrect, because it wasn't adjusted as I was doing in my case statement, or the seconds were not adjusted, which I also did in the other case statement I sent.  I also found that the case where I adjusted the fraction part because it was negative still had another issue, which was that it was never adjusted for position.So since this is for a one-time converter, which doesn't have to be optimized to the extreme, I rewrote my version, and made it into a function, and I call that function inside my select.  My version now looks like this, and I haven't found any problems with it yet:But, I must say it is interested to try to figure out the optimized version.  It's just that the possible adjustment and the positioning of the fractional part, and the possible adjustment of the seconds part need to be taken into account.Thanks for all the help.</description><pubDate>Thu, 06 Sep 2012 14:32:08 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]Lynn Pettis (9/6/2012)[/b][hr][quote][b]Steven Willis (9/6/2012)[/b][hr][quote][b]ScottPletcher (9/6/2012)[/b][hr][quote]return an INT value, which at a precision level of 7 gets overflowed.[/quote]The INT can't overflow returning billionths of a second -- the max possible value is 99,999,999, which is safely within an INT value range.[/quote]I stand corrected on the INT vs BIGINT. I tested it with INT and the solution above still works OK. So there's something else about the DATEDIFF for nanoseconds that can cause an overflow.  [/quote]The first select will work, the second will fail with an overflow:[code="sql"]SELECT DATEDIFF(ns,CAST('2012-09-06 13:50:00.000' AS DATETIME2),CAST('2012-09-06 13:50:02.000' AS DATETIME2))goSELECT DATEDIFF(ns,CAST('2012-09-06 13:50:0.000' AS DATETIME2),CAST('2012-09-06 13:50:03.000' AS DATETIME2))go[/code][/quote]That was dealing with DATE[b][u]PART[/u][/b] not DATEDIFF.DATEPART(NS, ...) can [b][u]never[/u][/b] exceed 999,999,999.</description><pubDate>Thu, 06 Sep 2012 14:08:41 GMT</pubDate><dc:creator>ScottPletcher</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]Steven Willis (9/6/2012)[/b][hr][quote][b]ScottPletcher (9/6/2012)[/b][hr][quote]return an INT value, which at a precision level of 7 gets overflowed.[/quote]The INT can't overflow returning billionths of a second -- the max possible value is 99,999,999, which is safely within an INT value range.[/quote]I stand corrected on the INT vs BIGINT. I tested it with INT and the solution above still works OK. So there's something else about the DATEDIFF for nanoseconds that can cause an overflow.  [/quote]The first select will work, the second will fail with an overflow:[code="sql"]SELECT DATEDIFF(ns,CAST('2012-09-06 13:50:00.000' AS DATETIME2),CAST('2012-09-06 13:50:02.000' AS DATETIME2))goSELECT DATEDIFF(ns,CAST('2012-09-06 13:50:00.000' AS DATETIME2),CAST('2012-09-06 13:50:03.000' AS DATETIME2))go[/code]</description><pubDate>Thu, 06 Sep 2012 13:53:33 GMT</pubDate><dc:creator>Lynn Pettis</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]ScottPletcher (9/6/2012)[/b][hr][quote]return an INT value, which at a precision level of 7 gets overflowed.[/quote]The INT can't overflow returning billionths of a second -- the max possible value is 99,999,999, which is safely within an INT value range.[/quote]I stand corrected on the INT vs BIGINT. I tested it with INT and the solution above still works OK. So there's something else about the DATEDIFF for nanoseconds that can cause an overflow.  </description><pubDate>Thu, 06 Sep 2012 13:37:04 GMT</pubDate><dc:creator>Steven Willis</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote]return an INT value, which at a precision level of 7 gets overflowed.[/quote]The INT can't overflow returning billionths of a second -- the max possible value is 999,999,999, which is safely within an INT value range.</description><pubDate>Thu, 06 Sep 2012 13:09:13 GMT</pubDate><dc:creator>ScottPletcher</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>That is because the accuracy of datetime2 is only to 100 nanoseconds.[b][url]http://msdn.microsoft.com/en-us/library/bb677335(v=sql.100).aspx[/url][/b]</description><pubDate>Thu, 06 Sep 2012 12:59:39 GMT</pubDate><dc:creator>Lynn Pettis</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Try this. The issue seems to be that the DATEDIFF and DATEPART functions seem to return an INT value, which at a precision level of 7 gets overflowed. So I broke it down and convert the nanosecond parts to BIGINT and subtract to get the difference as an integer. One interesting thing that I noticed with nanoseconds is that DATEDIFF returns 7 significant digits but always puts '00' on the end so a difference of 5448951 nanoseconds actually displays as '544895100'. Perhaps in later versions MS plans to allow a higher precision level for date/time functions?Just FYI, in the code below I added a value for days which may not be needed for your application.[code="sql"]DECLARE 	@StartTime DATETIME2(7)	,@EndTime DATETIME2(7)	,@TimeSpan TIME	SET @StartTime = '2012-04-26 13:53:43.0000000'SET @EndTime = '2012-04-26 13:54:44.5448951'--SET @StartTime = '2012-10-01 12:00:00.0130952'--SET @EndTime = '2012-10-01 17:00:04.9845083'SELECT     @StartTime AS stime    ,@EndTime AS etime    ,RIGHT('00' + CONVERT(VARCHAR,DATEDIFF(day,@StartTime,@EndTime)),2)	+ ':' + RIGHT('00' + CONVERT(VARCHAR,DATEDIFF(hour,@StartTime,@EndTime) % 24),2)	+ ':' + RIGHT('00' + CONVERT(VARCHAR,DATEDIFF(minute,@StartTime,@EndTime) % 60),2)	+ ':' + RIGHT('00' + CONVERT(VARCHAR,(DATEDIFF(second,@StartTime,@EndTime)) % 60),2)	+ '.' + RIGHT('0000000' + CONVERT(VARCHAR,(CAST((CAST(CAST(DATEPART(nanosecond,@EndTime) AS BIGINT) AS DECIMAL(18,8))/100) - (CAST(CAST(DATEPART(nanosecond,@StartTime) AS BIGINT) AS DECIMAL(18,8))/100) AS BIGINT))),7) AS ndiff[/code]</description><pubDate>Thu, 06 Sep 2012 12:43:11 GMT</pubDate><dc:creator>Steven Willis</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]ChrisM@Work (9/6/2012)[/b][hr]One more:[code="sql"]     	TimeResult3	= CAST(		DATEADD(ns,ABS(DATEPART(ns,btime)-DATEPART(ns,atime)),			DATEADD(ss,ABS(DATEDIFF(ss, aTime, btime)),CAST('1900-01-01 00:00' AS datetime2))) 		AS TIME(7))[/code][/quote]Aarrgghh!! They all fall over given suitable edge cases in the data.DATEDIFF counts boundaries - if there's a few nanoseconds difference between two dates but a seconds boundary is crossed, DATEDIFF(second... returns 1 second. So, revising the above code, and including Scott's (which [i]doesn't[/i] have this problem but fails with startdate more recent than enddate as he pointed out);[code="sql"];With MyCTE (ID, aTime, bTime)AS(	SELECT 1, CONVERT(datetime2,'1900-01-01 00:08:00.0000001'), CONVERT(datetime2,'1900-01-01 00:09:18.361') 	UNION ALL SELECT  2, '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705'	UNION ALL SELECT  3, '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001'	UNION ALL SELECT  4, '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'	UNION ALL SELECT  5, '1900-01-01 00:00:00.0000001', '1900-01-01 00:00:00.0000002'	UNION ALL SELECT  6, '1900-01-01 00:00:00.0000002', '1900-01-01 00:00:00.0000001'	UNION ALL SELECT  7, '1900-01-01 00:10:00.0000001', '1900-01-01 00:00:00.0000002'	UNION ALL SELECT  8, '1900-01-01 00:10:01.9999988', '1900-01-01 00:10:00.0000022'	UNION ALL SELECT  9, '1900-01-01 00:10:00.9999998', '1900-01-01 00:10:01.0000001'	UNION ALL SELECT 10, '1900-01-01 00:10:00.0000023', '1900-01-01 00:10:01.0000022'	UNION ALL SELECT 11, '1900-01-01 00:10:00.0000022', '1900-01-01 00:10:01.0000022'	UNION ALL SELECT 12, '1900-01-01 00:10:00.0000021', '1900-01-01 00:10:01.0000022')SELECT     aTime,     bTime,        SimpleProof = CAST(DATEADD(ms,ABS(DATEDIFF(ms,aTime, bTime)),CAST(CAST(0 AS DATETIME) AS DATETIME2)) AS TIME(3)),    	TimeResult1 = -- ChrisM 		CAST(DATEADD(ns,              (CASE WHEN aTime &amp;lt; bTime 					THEN DATEPART(ns,bTime)-DATEPART(ns,aTime)					ELSE DATEPART(ns,aTime)-DATEPART(ns,bTime) END),                   DATEADD(ss,                     ABS(DATEDIFF(ss,aTime,bTime)),                    CAST('1900-01-01 00:00' AS datetime2))              ) AS TIME(7)),        	TimeResult2 = -- Tardy ChrisR		CAST(DATEADD(nanosecond,            CASE                 WHEN Sec = 0 THEN ABS(NanoSec)                WHEN Sec &amp;lt; 0 THEN NanoSec * -1                ELSE NanoSec            END,            DATEADD(second,                ABS(Sec),                CAST('1900-01-01 00:00' AS datetime2))        ) AS TIME(7)),      	TimeDiff = -- ScottP		CONVERT(varchar(8), DATEADD(SECOND, DATEDIFF(SECOND, StartTime, EndTime)			- CASE WHEN DATEPART(NANOSECOND, StartTime) &amp;gt; DATEPART(NANOSECOND, EndTime) THEN 1 ELSE 0 END, 0), 108) +		'.' + RIGHT(REPLICATE('0', 7) +		CAST(((CASE WHEN DATEPART(NANOSECOND, StartTime) &amp;gt; DATEPART(NANOSECOND, EndTime) THEN 1000000000 ELSE 0 END +		DATEPART(NANOSECOND, EndTime) - DATEPART(NANOSECOND, StartTime)) / 100) AS varchar(7)), 7)  From MyCTECROSS APPLY (	SELECT         Sec = (DATEDIFF(second, aTime, btime)),        NanoSec = (DATEPART(ns,btime)-DATEPART(ns,atime)),        StartTime = CASE WHEN aTime &amp;lt; bTime THEN aTime ELSE bTime END,         EndTime = CASE WHEN aTime &amp;lt; bTime THEN bTime ELSE aTime END       ) x[/code]</description><pubDate>Thu, 06 Sep 2012 08:50:12 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>One more:[code="sql"]     	TimeResult3	= CAST(		DATEADD(ns,ABS(DATEPART(ns,btime)-DATEPART(ns,atime)),			DATEADD(ss,ABS(DATEDIFF(ss, aTime, btime)),CAST('1900-01-01 00:00' AS datetime2))) 		AS TIME(7))[/code]</description><pubDate>Thu, 06 Sep 2012 04:53:05 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Nice one, Paul.Here are two different one-line TSQL solutions:[code="sql"];With MyCTE (aTime, bTime)AS(	SELECT CONVERT(datetime2,'1900-01-01 00:08:00.0000001'), CONVERT(datetime2,'1900-01-01 00:09:18.361') 	UNION ALL SELECT '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705'	UNION ALL SELECT '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001'	UNION ALL SELECT '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'	UNION ALL SELECT '1900-01-01 00:00:00.000000111', '1900-01-01 00:00:00.000000222'	UNION ALL SELECT '1900-01-01 00:10:00.000000111', '1900-01-01 00:00:00.000000222')SELECT     aTime,     bTime, 	SimpleProof = CAST(DATEADD(ms,ABS(DATEDIFF(ms,aTime, bTime)),CAST(CAST(0 AS DATETIME) AS DATETIME2)) AS TIME(3)),     -- Method 1 (Chris R - too shy to post)       TimeResult1	= CAST(        DATEADD(            NS,            ABS(CAST(SUBSTRING(CAST(btime as varchar(30)),20,8) AS float) -                 CAST(SUBSTRING(CAST(atime as varchar(30)),20,8) AS float)                                ) *1000000000,            DATEADD(                SS,                 ABS(DATEDIFF(SS, aTime, btime)),                CAST('1900-01-01 00:00' AS datetime2))            )        AS time(7)),       -- Method 2 (Chris M)    	TimeResult2	= CAST(		CONVERT(VARCHAR(8),			DATEADD(second,ABS(DATEDIFF(second,aTime, bTime)),0),108) + '.' 			+ RIGHT('000000000' 				+ CAST(ABS(					DATEDIFF(ns,						DATEADD(second,DATEDIFF(second,aTime, bTime),aTime),						bTime)) 				AS VARCHAR)				,9) 		AS TIME(7))        From myCTE[/code]</description><pubDate>Thu, 06 Sep 2012 04:05:13 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>This looks like a thread without a one-line SQLCLR solution yet :w00t:-- see later post for updated code --</description><pubDate>Thu, 06 Sep 2012 03:31:25 GMT</pubDate><dc:creator>Paul White</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>[quote][b]bmahf (9/5/2012)[/b][hr]Oops, the s_difference+1 is incorrect.  That should be been just s_difference.  The minus is correct.[/quote]Here's a version which corrects for aTime being more recent than bTime, and includes a filter designed to return rows where the algorithm falls over. I've set it up with multiple CROSS APPLY operators as before, because a cascaded CROSS APPLY like this is much easier to understand and debug. Once the code is verified, the cCA can be "compacted down". [code="sql"]WITH MyCTE (aTime, bTime)AS(	SELECT CONVERT(datetime2,'1900-01-01 00:08:00.0000001'), CONVERT(datetime2,'1900-01-01 00:09:18.361') 	UNION ALL SELECT '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705'	UNION ALL SELECT '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001'	UNION ALL SELECT '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'	UNION ALL SELECT '1900-01-01 00:00:00.000000111', '1900-01-01 00:00:00.000000222'	UNION ALL SELECT '1900-01-01 00:10:00.000000111', '1900-01-01 00:00:00.000000222')SELECT 	*From myCTE a1CROSS APPLY (SELECT SecondsDifferenceINT = DATEDIFF(second,aTime, bTime)) aCROSS APPLY (SELECT AdjustedFirstDateDT = DATEADD(second,SecondsDifferenceINT,aTime)) bCROSS APPLY (SELECT NanosecondRemainderINT = DATEDIFF(ns,AdjustedFirstDateDT,bTime)) c-- use ABS() to convert seconds difference to a positive number-- where aTime is more recent than bTimeCROSS APPLY (SELECT TimeToSecondsDT = DATEADD(second,ABS(SecondsDifferenceINT),0)) dCROSS APPLY (SELECT TimeToSecondsVC = CONVERT(VARCHAR(8),TimeToSecondsDT,108)) eCROSS APPLY (SELECT ResultVC = e.TimeToSecondsVC + '.' 	+ RIGHT('000000000'+CAST(NanosecondRemainderINT AS VARCHAR),9)) fCROSS APPLY (	SELECT 		TimeResult	= CAST(f.ResultVC AS TIME(7)),		SimpleProof = CAST(DATEADD(ms,ABS(DATEDIFF(ms,aTime, bTime)),CAST(CAST(0 AS DATETIME) AS DATETIME2)) AS TIME(3))) g-- Filter for exceptions - this will return rows where the algorithm fails-- (if SQL Server doesn't bork first).WHERE CAST(TimeResult AS DATETIME) &amp;lt;&amp;gt; CAST(SimpleProof AS DATETIME)[/code]</description><pubDate>Thu, 06 Sep 2012 02:18:55 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>I saw that you had made an extremely compact version.  Haven't had time to check it out yet, but it looks pretty good at a glance.Thanks for all the help...Bruce</description><pubDate>Wed, 05 Sep 2012 15:54:56 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Oops, the s_difference+1 is incorrect.  That should be been just s_difference.  The minus is correct.</description><pubDate>Wed, 05 Sep 2012 15:54:12 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>I think you avoid all the CROSS APPLYs, as below.As written the code just ignores anything beyond 24 hrs, but if you needed to, you could add a check for that.[code="sql"]SELECT    StartTime, EndTime,    CONVERT(varchar(8), DATEADD(SECOND, DATEDIFF(SECOND, StartTime, EndTime)        - CASE WHEN DATEPART(NANOSECOND, StartTime) &amp;gt; DATEPART(NANOSECOND, EndTime) THEN 1 ELSE 0 END, 0), 108) +    '.' + RIGHT(REPLICATE('0', 7) +    CAST(((CASE WHEN DATEPART(NANOSECOND, StartTime) &amp;gt; DATEPART(NANOSECOND, EndTime) THEN 1000000000 ELSE 0 END +    DATEPART(NANOSECOND, EndTime) - DATEPART(NANOSECOND, StartTime)) / 100) AS varchar(7)), 7) AS TimeDiffFROM SourceTableORDER BY ID[/code]</description><pubDate>Wed, 05 Sep 2012 14:28:47 GMT</pubDate><dc:creator>ScottPletcher</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>I had also forgotten to adjust the seconds.  When the earlier date has a larger fractional part than the later date, as well as adding the fractional part to 1000000000, I needed to be subtracting 1 from s_difference, the difference in seconds.  I changed the query again so that the CROSS APPLY to calculate tt is as follows:[code="sql"]CROSS APPLY (SELECT tt = case when nsfraction &amp;lt; 0 then DATEADD(second, s_difference - 1, 0)							else DATEADD(second, s_difference + 1, 0)						end) d[/code]One more thing about the original code, it takes into account the case where the timespan is greater than a day, which is very nice, since, as much as my client assures me that will never happen, I've been assured of many things in my time.  This code will not break if that eventuality ever comes about.</description><pubDate>Wed, 05 Sep 2012 12:26:10 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Ok, that's interesting.  I didn't see the first of these, and so I sent another version, thinking I'd forgotten, somehow, to click Post.  Then I realized I had to go to page 2 to see it.  That's very embarrassing.  :)</description><pubDate>Wed, 05 Sep 2012 11:38:09 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>I forgot to mention that the first part of my case statement checks to see if the nsFraction is negative.  This can happen even though the overall first date is less than the second date, since the fraction part of the first can still be larger than the fraction part of the second.  So I added a case where if the nsFraction is negative, I add it to 1000000000 before casting to varchar.  This fixes the problem of a negative nsFraction.If you can do this with another fix to the query(ies) you showed, that would be very interesting to see.Thanks...Bruce</description><pubDate>Wed, 05 Sep 2012 11:36:35 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Actually, I did forget to mention that my case was also taking care of the case where the fraction of the first date is larger than the fraction of the second date.  So if you have a first date built using '1900-01-01 00:08:00.367', and a second date using '1900-01-01 00:09:18.361', you'll get a f.g of 00:01:18.0-6000000.  This is because, even though the first date is actually earlier than the second, the fraction part is larger, and so you end up with a -6000000 as nsFraction.  So in my case, I said if nsFraction is &amp;lt; 0, then add to nsFraction to 1000000000 to get the correct nanoseconds with correct fractional positioning.So there are two issues with your original query: the issue of losing position for the fractional part, and the issue where the fractional part, after doing the diff, turns out to be negative.Do you have another fix for the negative issue?  I'd really like to see your take on this.</description><pubDate>Wed, 05 Sep 2012 11:09:43 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>This might be better than the CASE:[code="sql"]With MyCTE (aTime, bTime)AS( SELECT convert(datetime2,'1900-01-01 00:08:00.0000001'), convert(datetime2,'1900-01-01 00:09:18.361')  UNION ALL SELECT '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705' UNION ALL SELECT '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001' UNION ALL SELECT '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001'	  UNION ALL SELECT '1900-01-01 00:00:00.000000111', '1900-01-01 00:00:00.000000222')SELECT 	*,	CAST(f.q AS TIME(7))From myCTE a1CROSS APPLY (SELECT s_difference = DATEDIFF(second,aTime, bTime)) aCROSS APPLY (SELECT axTime = DATEADD(second,s_difference,aTime)) bCROSS APPLY (SELECT nsFraction = DATEDIFF(ns,axTime,bTime)) cCROSS APPLY (SELECT tt = DATEADD(second,s_difference,0)) dCROSS APPLY (SELECT t = CONVERT(VARCHAR(8),tt,108)) eCROSS APPLY (SELECT q = e.t + '.' 	+ RIGHT('000000000'+CAST(DATEDIFF(ns,DATEADD(second,s_difference,aTime),bTime) AS VARCHAR),9)) f[/code]Here's another model after some fiddling around:[code="sql"]With MyCTE (aTime, bTime)AS( SELECT convert(datetime2,'1900-01-01 00:08:00.0000001'), convert(datetime2,'1900-01-01 00:09:18.361')  UNION ALL SELECT '1900-01-01 00:08:00.0000001', '1900-01-01 00:13:50.705' UNION ALL SELECT '1900-01-01 00:09:18.361', '1900-01-01 03:13:50.7050001' UNION ALL SELECT '1900-01-01 23:09:18.361', '1900-01-02 02:13:50.7050001' UNION ALL SELECT '1900-01-01 00:00:00.000000111', '1900-01-01 00:00:00.000000222')SELECT 	aTime, 	bTime,	Result = CAST(f.q AS TIME(7)),	SimpleProof = DATEADD(ms,DATEDIFF(ms,aTime, bTime),CAST(CAST(0 AS DATETIME) AS DATETIME2))From myCTE a1CROSS APPLY (SELECT s_difference = DATEDIFF(second,aTime, bTime)) aCROSS APPLY (	SELECT q = CONVERT(VARCHAR(8),DATEADD(second,s_difference,0),108) + '.' 	+ RIGHT('000000000'+CAST(DATEDIFF(ns,DATEADD(second,s_difference,aTime),bTime) AS VARCHAR),9)) f;[/code]</description><pubDate>Wed, 05 Sep 2012 09:55:11 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>That's great!!!  Thanks.  I had to make a slight change because if the nsFraction part is small, when it is cast to varchar, it should have leading zeroes to put it in the right place, but it doesn't.  So I changed it to the following code.  This is exactly the same as yours, but I added a few more datetime2 entries for more testing, and functionally, I added a case statement to the select that assigns to q.  This case statement, kind of laboriously, makes sure that the correct place is kept for the fractional part.[code="sql"]With MyCTE (TheTime)AS( SELECT convert(datetime2,'1900-01-01 00:08:33.580') UNION ALL SELECT '1900-01-01 00:08:32.579' UNION ALL SELECT '1900-01-01 00:08:32.581' UNION ALL SELECT '1900-01-01 00:09:18.361' UNION ALL SELECT '1900-01-01 00:13:50.705'  )SELECT 	*,	CAST(f.q AS TIME(7))From myCTE a1CROSS JOIN myCTE a2CROSS APPLY (SELECT s_difference = DATEDIFF(second,a1.TheTime, a2.TheTime)) aCROSS APPLY (SELECT aTime = DATEADD(second,s_difference,a1.TheTime)) bCROSS APPLY (SELECT nsFraction = DATEDIFF(ns,aTime,a2.TheTime)) cCROSS APPLY (SELECT tt = DATEADD(second,s_difference,0)) dCROSS APPLY (SELECT t = CONVERT(VARCHAR(8),tt,108)) eCROSS APPLY (SELECT q = case when nsfraction &amp;lt; 0 then e.t + '.' + CAST(1000000000 + nsFraction AS VARCHAR)							 when nsfraction &amp;lt; 10 then e.t + '.00000000' + CAST(nsFraction AS VARCHAR)							 when nsfraction &amp;lt; 100 then e.t + '.0000000' + CAST(nsFraction AS VARCHAR)							 when nsfraction &amp;lt; 1000 then e.t + '.000000' + CAST(nsFraction AS VARCHAR)							 when nsfraction &amp;lt; 10000 then e.t + '.00000' + CAST(nsFraction AS VARCHAR)							 when nsfraction &amp;lt; 100000 then e.t + '.0000' + CAST(nsFraction AS VARCHAR)							 when nsfraction &amp;lt; 1000000 then e.t + '.000' + CAST(nsFraction AS VARCHAR)							 when nsfraction &amp;lt; 10000000 then e.t + '.00' + CAST(nsFraction AS VARCHAR)							 when nsfraction &amp;lt; 100000000 then e.t + '.0' + CAST(nsFraction AS VARCHAR)							 else e.t + '.' + CAST(nsFraction AS VARCHAR)						end) fWHERE a1.TheTime &amp;lt; a2.TheTime	[/code]If you have a better way of going about this, I would like to see it.  Your code was very succinct, elegant, and a great deal quicker I'm sure than what I was working on doing.Thanks...Bruce</description><pubDate>Wed, 05 Sep 2012 09:37:07 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Tricky but not impossible: this is just a proof of concept.[code="sql"]With MyCTE (TheTime)AS( SELECT convert(datetime2,'1900-01-01 0:08:00.0000001') UNION ALL SELECT '1900-01-01 0:09:18.361' UNION ALL SELECT '1900-01-01 0:13:50.705'  )SELECT 	*,	CAST(f.q AS TIME(7))From myCTE a1CROSS JOIN myCTE a2CROSS APPLY (SELECT s_difference = DATEDIFF(second,a1.TheTime, a2.TheTime)) aCROSS APPLY (SELECT aTime = DATEADD(second,s_difference,a1.TheTime)) bCROSS APPLY (SELECT nsFraction = DATEDIFF(ns,aTime,a2.TheTime)) cCROSS APPLY (SELECT tt = DATEADD(second,s_difference,0)) dCROSS APPLY (SELECT t = CONVERT(VARCHAR(8),tt,108)) eCROSS APPLY (SELECT q = e.t + '.' + CAST(nsFraction AS VARCHAR)) fWHERE a1.TheTime &amp;lt; a2.TheTime	[/code]</description><pubDate>Wed, 05 Sep 2012 07:39:29 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Sorry about that.  Below, you can see that I have a source and a destination table, with names changed to protect the innocent.  The source table has two datetime2(7) fields, and the destination table has one time(7) field.  All other fields in the source table are duplicated in the destination table.  This is because I am converting the data in the source into the correct format for the destination, which amounts to just copying all fields over except the date/time fields, and for the date/time fields, I want to take the two datetime2(7) dates, get a time span as the difference between the two dates (which as said before is never going to be more than a few hours difference).  This time span needs to be stored as a time(7) data type.So the questions I'm trying to find an answer for are, how do I first get the time span difference between the two, and how do I then get that into a time(7) data format.  I would think this should be pretty easy, because in most higher level languages, there are one-liners for doing something like this.  But I haven't yet found a one-liner for doing this.[code="other"]SourceTable {  ID identity int,  StartTime datetime2(7),  EndTime datetime2(7),  SomeField1 int,  SomeField2 varchar(128),  SomeField3 double}DestinationTable {  ID identity int,  TimeSpan time(7),  SomeField1 int,  SomeField2 varchar(128),  SomeField3 double}SourceTable (data):ID  StartTime                    EndTime                      SomeField1  SomeField2  SomeField3 1  2012-04-26 13:53:43.0000000  2012-04-26 13:54:44.5448951        1234  dummytext1  9853.12354 2  2012-10-01 12:00:00.0130952  2012-10-01 17:00:04.9845083       24778  dummytext2       325.0The above table data needs to be processed so that it becomes the below expected destination data:DestinationTable (data):ID  TimeSpan          SomeField1  SomeField2  SomeField3 1  00:01:01.5448951        1234  dummytext1  9853.12354 2  05:00:04.9714131       24778  dummytext2       325.0[/code]The problems I've run into so far are:1) I tried using datediff for nanoseconds (since I want to keep the level of precision at 7 places), but I got the error "The datediff function resulted in an overflow".  And anyway, I don't really see a way to convert the integer result into time(7) data.  An example of what I did to produce this error is as follows:   declare @dt1 datetime2(7) = convert (datetime2, '2012-04-26 13:53:43.0')   declare @dt2 datetime2(7) = convert (datetime2, '2012-04-26 14:54:44.5448951')   select datediff(nanosecond, @dt1, @dt2)2) I tried merely subtracting the earlier datetime2 from the later datetime2, but got the error "Operand data type datetime2 is invalid for subtract operator".  At least with this I would have expected the result to be a datetime2, which I could then just grab the time part from, but it is not allowed for datetime2.  And example of this is:   declare @dt1 datetime2(7) = convert (datetime2, '2012-04-26 13:53:43.0')   declare @dt2 datetime2(7) = convert (datetime2, '2012-04-26 14:54:44.5448951')   select datediff(nanosecond, @dt1, @dt2)3) I am now looking at getting strings for each datetime2 and splitting them to get the hours, minutes, seconds, and nanoseconds strings, and then convert these to integer and do the timespan calculation myself, with hours, minutes, seconds, and nanoseconds as the result, and then creating time(7) data from the result.  But this really seems to be so much more work than should be necessary.Hopefully this is enough information.  I'm just thinking it shouldn't be this hard, and so I'm wondering if I'm going in the wrong direction, and if there's just another way that someone would normally do this in transact sql.  It's not possible that I could be the first to try this.  :)Thanks again...</description><pubDate>Wed, 05 Sep 2012 06:34:06 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Here is my problem.  As good as your description of the process, I can't see what you are trying to accomplish.  You should post the DDL for the tables, some sample data for the tables (NOT PRODUCTION DATA), and the expected results when done based on the sample data.</description><pubDate>Tue, 04 Sep 2012 15:20:14 GMT</pubDate><dc:creator>Lynn Pettis</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Ok, so this isn't enough for what I need.  Here's what I'm actually trying to do.  I am writing a SQL script as a conversion process from an old to a new db schema.  For one table in particular, I need to take two dates in each field, and in the destination table, I need to write out the time difference between these two dates.  Due to the nature of the data being written to this table, the difference between these two dates will never be greater than a few hours.So what I need to do is take the difference between the two datetime2(7) fields in a record, and create a time(7), which contains the same precision in nanoseconds as the original datetime2(7) fields.What I originally thought I could do was to just subtract one date from another and then cast the result to a time(7), but when I do that I get the error message "Operand data type datetime2 is invalid for subtract operator".So I thought I'd use datediff, which now I know I can go down to nanoseconds, but when I try with something that has a difference of a little over an hour I get "The datediff function resulted in an overflow", with a suggestion that I use lower precision, but the precision is important to my customer for this application.So the next thing I'm thinking is to convert each datetime2 to a string, split into its parts, and then work the thing out for myself.  But I have a hard time believing that SQL Server's transact sql has no way of doing this for us.  Am I right?  Should I need to get down and dirty with this thing?  Or is there something I'm missing?</description><pubDate>Tue, 04 Sep 2012 15:09:05 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>You know, I only just thought of the fact I'd done a convert to milliseconds instead of microseconds, and then I checked with microseconds which only gives a precision of 6 places, but I didn't realize datediff does nanoseconds.  Thank you.  That is my answer as far as getting the precision.Thanks a lot...bruce</description><pubDate>Tue, 04 Sep 2012 14:43:17 GMT</pubDate><dc:creator>bmahf</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>the datetime2 datatype goes to 7 decimal places;can you show what it is you are trying to do?[code]With MyCTE (TheTime)AS( SELECT convert(datetime2,'1900-01-01 0:12:14.1241234') UNION ALL SELECT '1900-01-01 0:08:16.361' UNION ALL SELECT '1900-01-01 0:08:57.705'  ) SELECT * From myCTE	[/code]</description><pubDate>Tue, 04 Sep 2012 13:03:40 GMT</pubDate><dc:creator>Lowell</dc:creator></item><item><title>RE: Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Have you looked at DATETIME2 and TIME?  They can go to 7 decimal places in precision and DATADIFF will go to nanoseconds if I remember correctly.  Also, I think it only goes to 100 nanoseconds.  You'll have to check that in Books Online.</description><pubDate>Tue, 04 Sep 2012 13:03:10 GMT</pubDate><dc:creator>Lynn Pettis</dc:creator></item><item><title>Time as a high precision difference of dates</title><link>http://www.sqlservercentral.com/Forums/Topic1354126-392-1.aspx</link><description>Hi all,I am trying to get a high precision difference of dates in SQL Server 2008 R2, and can't seem to fine anything but datediff, which gives the difference down to 3 places for milliseconds.  So if I have a difference of dates that has 3 hours, 2 minutes, 12 seconds, and 9859381 in milliseconds, I will get 3:2:12.985.  I am looking for 3:2:12.9859381, and that is to be used as data to a time variable.  Any suggestions?  I've looked around and can't seem to find anything about getting a higher precision than 3 places.  And then I need to be able to convert the result to save in a Time variable with that level of precision.Thanks for any help...</description><pubDate>Tue, 04 Sep 2012 12:57:55 GMT</pubDate><dc:creator>bmahf</dc:creator></item></channel></rss>