How can I calculate the difference in days between

2019-05-30 02:13发布

问题:

I am writing a query where I need to calculate the number of days since a date that is stored in the database in the format "YYYYMMDD". Since this is not a Date datatype, I can't use native Date functions. What is the best way (performance-wise, readability-wise, etc.) to perform such a calculation in a SQL query.

回答1:

Best? Convert that old table to use real date columns.

Next best? Write a database function to convert YYMMDD to a real date. Alan Campin's iDate can help. You'd end up with something akin to select cvty2d(date1)-cvty2d(date2) from ...

Better than nothing? Write ugly SQL to convert the number to character, split the character up, add hyphens and convert THAT to a real date. That beast would look something like

select 
  date(
     substr(char(date1),1,4) concat 
     '-' concat 
     substr (char(date1),5,2) concat 
     '-' concat 
     substr(char(date1),7,2)
  )  - 
  date(
     substr(char(date2),1,4) concat 
     '-' concat 
     substr (char(date2),5,2) concat 
     '-' concat 
     substr(char(date2),7,2)
  )   
from ...

Edit The reason these gymnastics are necessary is that the DB2 DATE() function wants to see a string in the form of 'YYYY-MM-DD', with the hyphens being necessary.



回答2:

Which version of SQL are you running? SQL2008 has no issues with that format as a date datatype

Declare @something nvarchar(100)
set @Something = '20120112'

select dateadd(dd, 1, @Something)
select datediff(dd, @Something, getdate())

2012-01-13 00:00:00.000

118