Skip to content
Advertisement

How to set parameters to show data from a period of time in SQL?

I created a SQL stored procedure:

My thought is to set @start_date and @end_date default to Null but it can also show specific data from a period of time if user select to do so, which means:

  1. When I run the following code:

It will show all data from New York regardless of time.

  1. When I run the following code:

It will show data from New York during March 1st, 2020 to March 31st, 2020. How can I adjust my code to achieve this goal? It seems that my code lacks a connection between @start_date and @end_date.

Advertisement

Answer

You are pretty close – you just need to make use of greater than equal to (>=) and less than (<) instead of equals (=) for your comparisons.

Note 1: the dateadd(day, 1, @end_date) is to take into account any time part of begin_date, so you can set @end_date to 31 May 2020 and include any entries that fall on that day.

Note 2: Unless you wish to specify a time component of the incoming parameter I would use a date datatype to avoid any unexpected behaviour happening with this compare. In fact begin_date should probably also just be a date as I don’t think you normally track the time that someone starts.

As an aside if you default your parameters e.g.

You don’t have to explicitly pass them in e.g.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement