views:

4052

answers:

3

Hello,

I have a SP that has the following algorithm.

IF <SomeCondition>
BEGIN
  SELECT * FROM TABLE1
END
ELSE
BEGIN
  SELECT * FROM TABLE2
END
--Union the above with the query below
UNION
  SELECT * FROM TABLE3

The recordset returned is EXACTLY the same. I need to do a UNION of that resultset and another query.

Is there a way to do this without having to use a temp table?

+5  A: 

How about:

SELECT * FROM TABLE1 WHERE <SomeCondition>
UNION
SELECT * FROM TABLE2 WHERE NOT <SomeCondition>
UNION
SELECT * FROM TABLE3

If you're worried about evaluating twice:

DECLARE @condition bit
SET @condition = CASE WHEN <SomeCondition> THEN 1 ELSE 0 END

SELECT * FROM TABLE1 WHERE @condition = 1
UNION
SELECT * FROM TABLE2 WHERE @condition = 0
UNION
SELECT * FROM TABLE3
Andomar
+2  A: 

You could also use dynamic SQL if you don't mind that it isn't compiled. For example:

DECLARE @sql VARCHAR(100)
DECLARE @table VARCHAR(10)

IF <SomeCondition>
BEGIN
    SET @table = 'Table1'
END
ELSE
BEGIN
    SET @table = 'Table2'
END

SET @sql = 'SELECT * FROM ' + @table + ' UNION SELECT * FROM TABLE3'
EXEC(@sql)
Scott Anderson
A: 

Also if you can get by with UNION ALL instead of UNION, do so - may be cheaper to not eliminate duplicates

AlexKuznetsov