SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 UNION with IF clause
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Ciupaz
Posting Yak Master

Italy
232 Posts

Posted - 12/05/2012 :  08:08:18  Show Profile  Reply with Quote
Hello all,
in a my stored procedure, I have several SELECT combined to an UNION to get my results.
Something like this:


Select Field1,Field2
From TableA A inner join TableB B
On A.ID = B.ID

UNION

Select Field1,Field2
From TableC C inner join TableD D
On C.ID = D.ID

UNION

Select Field1,Field2
From TableE E inner join TableF F
On E.ID = F.ID


Then I have to add another Select block only if a condition is valid, like:


IF (@DataDaUTC<= @DataStartNBDO)

Select Field1,Field2
From TableY Y inner join TableZ Z
On Y.ID = Z.ID


but in this way does not work in SQL Server 2008.

How can I solve this problem?


Thanks in advance.


Luigi

sunitabeck
Flowing Fount of Yak Knowledge

5155 Posts

Posted - 12/05/2012 :  08:11:48  Show Profile  Reply with Quote
Instead of using the if clause, insert your condition as a where clause

....
UNION 

Select Field1,Field2
From TableE E inner join TableF F
On E.ID = F.ID

UNION

Select Field1,Field2
From TableY Y inner join TableZ Z
On Y.ID = Z.ID
WHERE @DataDaUTC<= @DataStartNBDO
Go to Top of Page

jimf
Flowing Fount of Yak Knowledge

USA
2869 Posts

Posted - 12/05/2012 :  08:14:21  Show Profile  Reply with Quote
Those params aren't part of the table, so brute force may work

IF @DataDaUTC <= @DataStartNBDO
Select Field1,Field2
From TableA A inner join TableB B
On A.ID = B.ID

UNION

Select Field1,Field2
From TableC C inner join TableD D
On C.ID = D.ID

UNION

Select Field1,Field2
From TableE E inner join TableF F
On E.ID = F.ID

UNION

Select Field1,Field2
From TableY Y inner join TableZ Z
On Y.ID = Z.ID


ELSE

Select Field1,Field2
From TableA A inner join TableB B
On A.ID = B.ID

UNION

Select Field1,Field2
From TableC C inner join TableD D
On C.ID = D.ID


Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

Ciupaz
Posting Yak Master

Italy
232 Posts

Posted - 12/05/2012 :  08:28:04  Show Profile  Reply with Quote
Thank you Sunita and Jim
I've adopted the Sunita's solution.

Luigi
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000