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.
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, Amountfrom table1where No = @var1union all select ID, Pcsfrom table2where 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, Amountfrom table1where No = @var1union all select ID, Pcsfrom table2where No = @var2AND @var2 > '' ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
KlausEngel
Yak Posting Veteran
85 Posts |
Posted - 2012-05-30 : 18:31:36
|
I had to modify my query select ID, Count(ID)from table1where No = @var1group by IDunion all select ID, COUNT(ID)from table2where 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? |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-05-30 : 19:21:00
|
select ID, Count(ID) AS Cntfrom table1where No = @var1group by IDunion all select *from(select ID, COUNT(ID) AS Cntfrom table2where No = @var2)tWHERE EXISTS(SELECT 1 WHERE @var2 > '') ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
KlausEngel
Yak Posting Veteran
85 Posts |
Posted - 2012-05-31 : 10:48:59
|
Great - thanks! |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-05-31 : 16:07:03
|
welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|