USE Northgale go CREATE PROCEDURE search_orders_4 @orderid int = NULL, @status char(1) = NULL, @fromdate date = NULL, @todate date = NULL, @minprice decimal(10,2) = NULL, @maxprice decimal(10,2) = NULL, @custid nchar(5) = NULL, @custname nvarchar(40) = NULL, @city nvarchar(25) = NULL, @region nvarchar(15) = NULL, @country nvarchar(15) = NULL, @prodid int = NULL, @prodname nvarchar(40) = NULL, @employeestr varchar(MAX) = NULL AS DECLARE @employeetbl TABLE (rowno int NOT NULL PRIMARY KEY, employeeid int NOT NULL UNIQUE) DECLARE @rowc int, @emp1 int, @emp2 int, @emp3 int, @emp4 int, @hasemptbl bit = 0 IF @employeestr IS NOT NULL BEGIN INSERT @employeetbl (rowno, employeeid) SELECT row_number() OVER(ORDER BY (SELECT 1)), n FROM intlist_to_tbl(@employeestr) SELECT @rowc = @@rowcount IF @rowc BETWEEN 1 AND 4 BEGIN SELECT @emp1 = employeeid FROM @employeetbl WHERE rowno = 1 SELECT @emp2 = employeeid FROM @employeetbl WHERE rowno = 2 SELECT @emp3 = employeeid FROM @employeetbl WHERE rowno = 3 SELECT @emp4 = employeeid FROM @employeetbl WHERE rowno = 4 END ELSE IF @rowc > 4 SELECT @hasemptbl = 1 END SELECT o.OrderID, o.OrderDate, o.EmployeeID, o.Status, c.CustomerID, c.CustomerName, c.Address, c.City, c.Region, c.PostalCode, c.Country, c.Phone, od.UnitPrice, od.Quantity, p.ProductID, p.ProductName, p.UnitsInStock, p.UnitsOnOrder FROM Orders o JOIN [Order Details] od ON o.OrderID = od.OrderID JOIN Customers c ON o.CustomerID = c.CustomerID JOIN Products p ON p.ProductID = od.ProductID WHERE (o.OrderID = @orderid OR @orderid IS NULL) AND (o.Status = @status OR @status IS NULL) AND (o.OrderDate >= @fromdate OR @fromdate IS NULL) AND (o.OrderDate <= @todate OR @todate IS NULL) AND (od.UnitPrice >= @minprice OR @minprice IS NULL) AND (od.UnitPrice <= @maxprice OR @maxprice IS NULL) AND (o.CustomerID = @custid OR @custid IS NULL) AND (c.CustomerName LIKE @custname + '%' OR @custname IS NULL) AND (c.City = @city OR @city IS NULL) AND (c.Region = @region OR @region IS NULL) AND (c.Country = @country OR @country IS NULL) AND (od.ProductID = @prodid OR @prodid IS NULL) AND (p.ProductName LIKE @prodname + '%' OR @prodname IS NULL) AND (o.EmployeeID IN (@emp1, @emp2, @emp3, @emp4) OR @emp1 IS NULL) AND (o.EmployeeID IN (SELECT employeeid FROM @employeetbl) OR @hasemptbl = 0) ORDER BY o.OrderID OPTION (RECOMPILE)