简体   繁体   中英

How should I store and validate date interval in SQL Server?

I want to store a date interval value for a given table, let's say that the start date is on July 1st 2016 and the end date is on June 30th 2017. The simplest way would be to set the value as it is (in SQL Server the datetime value July 1st 2016 is stored as 01/07/2016 00:00:00). Then, when I want to validate if a certain date is within the range of that interval, I would just use the BETWEEN clause, for example :

WHERE this_date BETWEEN start_date AND end_date

However, if this_date is set to a value 30/06/2017 10:00:00, the above statement will return false. To handle this, I imagine I would change the WHERE clause to this :

WHERE this_date BETWEEN start_date AND dateadd(ss, -1, datead(dd,1,end_date))

This way, the end_date value will be set to 30/06/2017 23:59:59 and the SQL clause would return true.

Another way to deal with this is to just store the end_date value containing the time signature ie 30/06/2017 23:59:59. That way, the WHERE clause does not need to be changed and the statement would return true.

I am leaning towards the second approach, but would like to hear your opinion. Would you say the second approach is more natural ? Are there cases where this would not be favorable ? Is there a better way to validate the date interval if I use the first approach ?

Your opinion is much appreciated!

You need to use Stored procedure to satisfy your needs like:

if(date>thisdate)
your query here;
else
another query here;

given logic;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM