I have a SQL stored procedure for a search page on a website where a user can search records by, and between, two date fields: initiatedDateStart and initiatedDateEnd. The logic for the SQL query should be as follows:
- If the startDate has a value, but the endDate is empty, or equal to the startDate, return records that were created ON the startDate.
- If the startDate has a value, and the endDate value is greater than
the startDate, return records that were created BETWEEN the two
dates.
Since I'm not a SQL expert, my stored procedure is not very elegant or clever, but it does return the records I expect it to, except for the date fields. I have researched for this, but the syntax and logic is stumping me. Here is a snippet of my stored procedure. If a value is entered in the initStartDate texbox, but the initEndDate is empty, this returns ALL the records created AFTER the start date. I appreciate any and all help on this.
DECLARE @initStartDate datetime = NULL DECLARE @initEndDate datetime = NULL SELECT DISTINCT d.[DCRId], d.[Title], d.[FiscalYear] FROM [dbo].[tblDCR] d LEFT OUTER JOIN [dbo].[tblWorkflow] orig ON (d.[DCRId] = orig.[DCRId] AND orig.StepName = 'Draft') WHERE 1 = 1 AND (orig.BadgeDate >= @initStartDate OR @initStartDate IS NULL) AND (orig.BadgeDate <= @initEndDate OR @initEndDate IS NULL)