Skip to content
Advertisement

Complex Conditional Query in Where Clause

In my company, each department has their own statuses for purchase orders. I’m trying to load only the pertinent POs for a specific user’s department. I keep getting errors. It seems like it should be correct, though. I initially attempted to use a Case statement, but it appears that SQL can only do a simple return from a case, so I’m now attempting If statements. Current error is Incorrect Syntax near the keyword IF. It looks right to me. It’s as if the incorrect syntax is that it is in the IN parentheses.

Advertisement

Answer

There’s a conceptual problem to address here first, and then we can look at how to actually do what you want.

select is starting a statement here. Statements end with a semicolon. You can’t put statements inside other statements. What you are doing is the same as trying to do something like this in c#:

You can of course use expressions inside statements:

Moreover, select is a declarative statement. You can’t do imperative flow of control inside a declarative language construct. You’re mixing metaphors, as it were. To understand the declarative/imperative distinction see this question and in particular (in my opinion) this answer.

So the first thing to do is wrap your head around the declarative nature of SQL statements like select. Yes, T-SQL also includes imperative constructs like if and while, but you can’t do imperative inside declarative.

You can use conditional expressions (and other expressions) inside a declarative statement:

In this example the declarative select says what to do with all of the rows returned by the from clause. I don’t write a while loop or a for loop in order to instruct the computer to loop over each row and provide instructions inside the loop. The from returns all the rows, and the select declares what I want to do with each of them. The case expression will be evaluated against every row in sys.types.

OK, so what about your specific question? There’s many ways to write the code. Here is one way that is very similar to your current structure. First I conditionally (imperatively!) populate a temp table with the statuses I want. Then I declaratively use that temp table as my filter:

Can I do it without the temp table? Sure. Here’s one way:

Here we evaluate a different in depending on the value of @dept. Clearly only one of them actually needs to be evaluated, and the other two don’t really need to be there, depending on which value of @dept is provided. Adding an option (recompile) can be beneficial in cases like this. For more information about option (recompile) look here and here.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement