I have this problem where I need to set “optional” parameters for my stored procedure to work fine.
For example, I have this:
CREATE PROCEDURE [dbo].[Search]
(
@StartTime datetime = NULL,
@EndTime datetime = NULL,
@CustomerEmail nvarchar(255) = NULL,
@OrderStatusID int
)
Now, in my .net website I have this like an example, please keep in mind that there can be only one parameter or there might be all of them:
commAdvanced.Parameters.Add("@StartTime", SqlDbType.DateTime).Value = startDate;
commAdvanced.Parameters.Add("@EndTime", SqlDbType.DateTime).Value = endDate;
commAdvanced.Parameters.Add("@CustomerEmail", SqlDbType.nvarchar).Value = null;
commAdvanced.Parameters.Add("@OrderStatusID", SqlDbType.Int).Value = null;
And this is the query:
SELECT * FROM Order
WHERE CreatedOn > CAST(@StartTime as datetime)
AND CreatedOn < CAST(@EndTime as datetime)
AND Order.OrderStatusID = @OrderStatusID
AND Order.CustomerEmail = @PaymentStatusID
I am getting no records when I am doing that, can someone please help me what do I need to change.
According to your question, out of 4 parameters either one or all parameters could be passed to your procedure. And your query has all the columns checked for in the where clause. So if I understand you right, currently, you will not get any records until all 4 parameters are passed with valid data.
Try this, I am simply constructing a query and then executing it. I check for each of the parameters for nulls and only the parameter values that are not null are included in the where clause.