SQL Server query to get the difference between two dates in two different columns

1.6k Views Asked by At

I would like to write a SQL Server query which should get the difference between two dates (i.e. dates are available in two columns named "Start date" and "End date"). I would like to find the difference between two dates in these two different columns and update in another column as "Expired" if the difference is -1 or below. Most importantly: The time should start from the specified start date and it should check periodically.

3

There are 3 best solutions below

0
On

You can use DATEDIFF and case when like this:

update table set expColumn = case when DATEDIFF(day,start_date,end_date) > 0 
       then 'Expired' end FROM table

Hope this helps.

0
On

To find the differential between two date values you use the DATEDIFF() function.

Also, depending on your requirements, you can set this up in your table as a Computed Column. That way any changes to the component columns in the computed column's definition will automatically update the computed column to reflect the new values.
With the PERSISTED keyword you can also allow the computed column to be indexed on. Check the documentation here for more details: https://technet.microsoft.com/en-us/library/ms191250%28v=sql.105%29.aspx

0
On

This is based on what I think you are trying to do, it's not exactly clear.

I don't think you want to add a column to your table to identify what is expired because that column would be dependant on the "End Date" column as well as the primary key which would violate the 3rd normal form. It really shouldn't be needed because you can query out which ones are expired at any time. I can't really think of a scenario where you would need to have a column that indicates expiry. You can create a query like others mentioned to display (not create) another column that marks the expired rows, or you can simply display only the ones expired, or it might make more sense to move them to a different table.

SET IDENTITY_INSERT ExpiredTableName ON 

INSERT INTO ExpiredTableName (Column1, Column2, StartDate, EndDate)
SELECT *
FROM TableName
WHERE DATEDIFF(day, InvoiceDate, '2015-04-20') >0

Identity Insert is for auto-generated keys only.

You can run your queries at regular time intervals like was already mentioned.