I’m fairly inexperienced with SQL. I’m using SQL Server 2012.
Basically I want the WHERE clause of a SQL SELECT statement to be adjusted depending on the values of certain parameters passed to the stored procedure.
I’ll also be UNIONing the result of this SELECT with another SELECT statement within the stored procedure.
The structure so far is as follows:
CREATE PROCEDURE dbo.procMyProcedure
@Param1 smallint = null
, @Param2 int = null
, ...
AS ...
--I have three separate SELECT statements, each catering for a specific scenario
SELECT ...
FROM ...
WHERE
(ER.EMR_Number = ISNULL(@Param1, ER.EMR_Number)) AND
(EE.EME_Number = ISNULL(@Param2, EE.EME_Number))
SELECT ...
FROM ...
WHERE
(EE.EME_Number = ISNULL(@Param2, EE.EME_Number))
SELECT ...
FROM ...
WHERE
(ER.EMR_Number = ISNULL(@Param1, ER.EMR_Number))
The statements are identical except for the WHERE clause. In my scenario, the first statement returns exactly 1 result. The second returns 119 results. The third returns 3 results.
I don’t want to run all three statements. I want to merge them into one statement, with that single statement returning the same results as the three statements above, depending on the values of the passed (optional) parameters.
I can do this by wrapping the SELECTs in a nested IF … ELSE IF structure, but then I can’t use UNION. The following structure doesn’t work:
IF ...
SELECT ...
ELSE IF ...
SELECT ...
ELSE IF ...
SELECT ...
UNION
SELECT ...
There must be a way to merge these into a single SELECT statement, in such a way that I can use it as part of a UNION statement.
I want to get to the following:
SELECT ... --This select
UNION
SELECT ... --Other stuff
I’d really appreciate any help with this.
Regards,
Adam.
OK. I’ve figured a solution to my problem. It involves some Boolean logic and some use of NULL and a fair number of brackets.
Here’s the WHERE clause I was looking for:
It gives me the exact results I expected, AND I can still use the query in a UNION statement.
Of course, there may be a more elegant solution. If so, please post.
-Adam.