Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 - If condition with union

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?

like image 568
Bob Smith Avatar asked Apr 21 '26 18:04

Bob Smith


2 Answers

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
like image 108
Andomar Avatar answered Apr 24 '26 06:04

Andomar


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)
like image 23
Scott Anderson Avatar answered Apr 24 '26 07:04

Scott Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!