I am trying to create a simple view in Microsoft SQL Server Management Studio 2008 R2. I tried using the Views > New View designer as well as typing the CREATE VIEW command directly in to the query builder, but no matter how I create it, the studio malforms my query.
Here is the source query. Pay special attention to the WHERE clause:
SELECT RTRIM(Orders.ITEMNUMBER) AS ItemNumber,
Orders.Type,
Orders.Quantity,
Orders.OrderNumber,
OrderDetails.SaleDate,
OrderLineItems.ReturnType,
OrderLineItems.Action,
OrderLineItems.Restock,
OrderLineItems.Return
FROM Orders
INNER JOIN OrderDetails ON Orders.Type = OrderDetails.Type
AND Orders.OrderNumber = OrderDetails.OrderNumber
INNER JOIN OrderLineItems ON Orders.OrderNumber = OrderLineItems.OrderNumber
WHERE (OrderLineItems.Type = 'INVOICE' AND Orders.Type='3') OR
(OrderLineItems.Type = 'RETURN' AND Orders.Type='4')
However, no matter what, SQL Server Management Studio malforms the query to this:
SELECT RTRIM(Orders.ITEMNUMBER) AS ItemNumber,
Orders.Type,
Orders.Quantity,
Orders.OrderNumber,
OrderDetails.SaleDate,
OrderLineItems.ReturnType,
OrderLineItems.Action,
OrderLineItems.Restock,
OrderLineItems.Return
FROM Orders
INNER JOIN OrderDetails ON Orders.Type = OrderDetails.Type
AND Orders.OrderNumber = OrderDetails.OrderNumber
INNER JOIN OrderLineItems ON Orders.OrderNumber = OrderLineItems.OrderNumber
WHERE (OrderLineItems.Type = 'INVOICE') AND (Orders.Type='3') OR
(OrderLineItems.Type = 'RETURN') AND (Orders.Type='4')
See, the difference is that I want to pull rows where OrderLineItems.Type is INVOICE and Orders.Type is 3, OR OrderLineItems.Type is RETURN and Orders.Type is 4. The query it rewrites for me messes up the parentheses - it won't allow me to put two AND clauses on either side of an OR clause.
Is there any way to bypass Microsoft's query rewriter? Or would the above rewritten query still be interpreted correctly even though the parentheses are not properly separating the two AND clauses?
As I mentioned, I already tried creating this using a straight up CREATE query in the New Query view, but it still ends up malformed.
Thanks for your help.
EDIT / Conclusion
So it turns out that both queries above are logically equivalent. MS SQL's order of operations causes it to evaluate each AND statement first, then finally check the OR statement last. The parentheses, though nice for clarity, were unnecessary.