I need to retrieve data by selected dates. There is one major detail: user can select two days one after another, and then it can skip some days, and then select another ones.
What is the best way to pass selected dates into a stored procedure and organize filter by such date ranges?
For example, I have the table with the following structure:
CREATE TABLE [dbo].[Events](
[ID] [int] IDENTITY(1,1) NOT NULL,
[EventDate] [datetime] NOT NULL,
[Amount] [float] NOT NULL,
CONSTRAINT [PK_Events] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
With the following data:
INSERT [dbo].[Events] ([EventDate], [Amount]) VALUES ('2012-01-01 10:00', 12)
INSERT [dbo].[Events] ([EventDate], [Amount]) VALUES ('2012-01-01 11:00', 154)
INSERT [dbo].[Events] ([EventDate], [Amount]) VALUES ('2012-01-01 12:00', 4)
INSERT [dbo].[Events] ([EventDate], [Amount]) VALUES ('2012-02-01 10:00', 132)
INSERT [dbo].[Events] ([EventDate], [Amount]) VALUES ('2012-02-01 11:00', 212)
INSERT [dbo].[Events] ([EventDate], [Amount]) VALUES ('2012-03-01 10:00', 712)
INSERT [dbo].[Events] ([EventDate], [Amount]) VALUES ('2012-03-01 20:00', 892)
User wants to retrieve data with Event Date from 2012-01-01 10:00 and 2012-01-01 11:00,
from 2012-03-01 09:00 to 2012-03-01 19:00, etc.
User can select different count of intervals.
If you want to send multiple “identical” parameters to a stored procedure, that would usually indicate that you should use Table Valued Parameters (TVPs).
Within the stored procedure, you can treat the TVP as a table variable, so your query would look like:
Assuming your TVP has two columns,
FromDateandToDatewith obvious definitions.