Darrell Norton's Blog [MVP]

Sponsors

The Lounge

News

  • Darrell Norton pic

    MVP logo

    View Darrell Norton's profile on LinkedIn

    Currently Reading:

    weewar.com

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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)


Posted 06-23-2003 10:20 AM by Darrell Norton

[Advertisement]