CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Darrell Norton's Blog [MVP]

Fill in description here...

Re: Optional Parameters in SQL Server Search Queries

Steve Eichert writes a good post on keeping search queries clean using optional paramters.  The example given works as long as the fields are all non-null.  If the fields can be null and you want to search on that field, you only have to modify the SQL query slightly.  For example, say ManagerID can be null (if the employee is the CEO of the company).

Before

SELECT * FROM Employees e
WHERE
(@EmployeeID IS NULL OR e.EmployeeID = @EmployeeID)
AND (@DepartmentID IS NULL OR e.DepartmentID = @DepartmentID)
AND (@ManagerID IS NULL OR e.ManagerID = @ManagerID)
AND (@LocationID IS NULL OR e.LocationID = @LocationID)

After (added text in red)

SELECT * FROM Employees e
WHERE
(@EmployeeID IS NULL OR e.EmployeeID = @EmployeeID)
AND (@DepartmentID IS NULL OR e.DepartmentID = @DepartmentID)
AND (@ManagerID IS NULL AND e.ManagerID IS NULL OR e.ManagerID = @ManagerID)
AND (@LocationID IS NULL OR e.LocationID = @LocationID)



Check out Devlicio.us!