Each of the parameters below is checked for NULL and if so returns true, thereby effectively bypassing the filter. If the parameter is NOT NULL, the parameter is used as a filter.
ALTER proc [dbo].[CollectsearchData]
@StartDate datetime,
@EndDate datetime,
@EmployeeID NVARCHAR(50),
@EmployeeName nvarchar(50)
AS
BEGIN
SELECT * from ViewEmployeeTest
WHERE
(@StartDate IS NULL OR joindate >= @StartDate)
AND
(@EndDate IS NULL OR joindate <= @EndDate)
AND
(@EmployeeID IS NULL OR EmployeeID = @EmployeID)
AND
(@EmployeeName IS NULL OR DriverName LIKE '%' + @EmployeeName + '%'
END
The value being passed into your C# function guarantees that you will never have a NULL as it is a DateTime rather than a nullable DateTime (represented by DateTime?). Correction to function definition is below:
public DataTable SearchDataA(string ConnectionString,string EmployeeNo,string EmployeeName, DateTime? StartDate, DateTime? EndDate)
All of the parameters need to be converted to DBNull.Value, if they are C# null.
Solution #1 is correct for the string parameters:
cmd.Parameters.Add("@EmployeeID", SqlDbType.NVarChar, 50).Value = EmployeeNo ?? DBNull.Value;
cmd.Parameters.Add("@EmployeeName", SqlDbType.NVarChar, 50).Value = EmployeeName ?? DBNull.Value;
Unfortunately, DateTime to DBNull.Value conversions are not compatible and must done with an if statement.
cmd.Parameters.Add("@StartDate", SqlDbType.DateTime);
cmd.Parameters.Add("@EndDate", SqlDbType.DateTime);
if(StartDate.HasValue)
{
cmd.Parameters["@StartDate"].Value = StartDate.Value;
}
else
{
cmd.Parameters["@StartDate"].Value = DBNull.Value;
}
if(EndDate.HasValue)
{
cmd.Parameters["@EndDate"].Value = EndDate.Value;
}
else
{
cmd.Parameters["@EndDate"].Value = DBNull.Value;
}
Hope this helps!