-1

I have a SQL Server instance and with a date table with datetime values. I have been trying to write queries to find the age of those columns by subtracting the current time value from the column values using GETDATE().

I have tried queries like the following:

enter image description here

but I'm getting errors like these:

enter image description here

Any help would he appreciated! Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JohnMenx
  • 9
  • 2

2 Answers2

0

Copied from Date difference formatted in Days Hours Minutes Seconds

DECLARE @date DATETIME = '2023/01/01 12:29:51'
      , @x INT
  
SET @x = DATEDIFF(S, @Date, GETDATE());

SELECT @date TestDate
     , CONVERT(VARCHAR(10), ( @x / 86400 )) + ' Days '
       + CONVERT(VARCHAR(10), ( ( @x % 86400 ) / 3600 )) + ' Hours '
       + CONVERT(VARCHAR(10), ( ( ( @x % 86400 ) % 3600 ) / 60 ))
       + ' Minutes ' + CONVERT(VARCHAR(10), ( ( ( @x % 86400 ) % 3600 ) % 60 ))
       + ' Seconds';
Tom Boyd
  • 385
  • 1
  • 7
0

Try this:

DECLARE @FirstDate  DATETIME2(3) = '2021-01-01 00:00:00.000'
       ,@SecondDate DATETIME2(3) = '2022-01-01 23:59:59.999';

DECLARE @BuffDate DATETIME2(3) = '2001-01-01 00:00:00.000';

SELECT CONCAT
       (
            DATEDIFF_BIG(MILLISECOND, @FirstDate, @SecondDate) / 86400000 
            ,' '
            ,CONVERT(VARCHAR, DATEADD(MILLISECOND, DATEDIFF_BIG(MILLISECOND, @FirstDate, @SecondDate) % 86400000, @BuffDate), 114)
       );

enter image description here

The idea is get the diff in milliseconds, the extract the day from the diff using / 86400000 . The rest part % 86400000 will be the milliseconds which are smaller then one day and can be converted to HH:MM:SS.MS.

Of course, you can play with the milliseconds precision.

gotqn
  • 42,737
  • 46
  • 157
  • 243