Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 check if variable exists

Author  Topic 

KlausEngel
Yak Posting Veteran

85 Posts

Posted - 2012-05-30 : 18:11:46
I have a query that depends on 2 parameters. It's a basic SELECT with a UNION ALL.

select ID, Amount
from table1
where No = @var1
union all
select ID, Pcs
from table2
where No = @var2

Is it possible to skip the second select statement when @var2 is NULL (or not set)?
Thanks.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-05-30 : 18:17:53
do you mean this?

select ID, Amount
from table1
where No = @var1
union all
select ID, Pcs
from table2
where No = @var2
AND @var2 > ''


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

KlausEngel
Yak Posting Veteran

85 Posts

Posted - 2012-05-30 : 18:31:36
I had to modify my query

select ID, Count(ID)
from table1
where No = @var1
group by ID
union all
select ID, COUNT(ID)
from table2
where No = @var2


This way the second select statement always returns a row even if @var2 is NULL, the count will be '0' but in that case I would rather have the second select statement not be executed. Does that makes sense?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-05-30 : 19:21:00


select ID, Count(ID) AS Cnt
from table1
where No = @var1
group by ID

union all

select *
from
(
select ID, COUNT(ID) AS Cnt
from table2
where No = @var2
)t
WHERE EXISTS(SELECT 1 WHERE @var2 > '')




------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

KlausEngel
Yak Posting Veteran

85 Posts

Posted - 2012-05-31 : 10:48:59
Great - thanks!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-05-31 : 16:07:03
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -